Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Ruby

Thành thạo ViewComponent: Hướng dẫn thực tế xây dựng View Components tái sử dụng trong Rails

Được cảm hứng từ React, ViewComponents là Ruby objects dùng để xây dựng markup cho rendering views. ViewComponent là framework xây dựng view components tái sử dụng, testable, và encapsulated trong Rails. Thông thường, reusable views trong Rails tạo bằng partials và render trong views khác khi cần, nhưng với ViewComponent gem, partials có thể thay bằng view components, vì chúng cung cấp nhiều lợi ích hơn. Hãy đi sâu vào lợi ích này.

Khi và Tại sao nên dùng ViewComponents?

Như nêu trước, view components tái sử dụng và testable. Do đó, áp dụng bất cứ khi nào view cần tái sử dụng hoặc được lợi từ test trực tiếp. Một số lợi ích view components, theo tài liệu, bao gồm:

  • Nhanh ~10x so với partials.
  • Là Ruby objects; method initialize rõ ràng định nghĩa yêu cầu render view. Điều này làm cho chúng dễ hiểu và tái sử dụng trong nhiều view khác. Hơn nữa, chất lượng code Ruby có thể enforce, giảm rủi ro bug.
  • Có thể unit test trái ngược với traditional Rails views yêu cầu integration tests cũng exercise routing và controller layers ngoài view.

Triển khai ViewComponent

ViewComponents là subclass của ViewComponent::Base và sống trong app/components. Tên kết thúc bằng -Component, và nên đặt tên theo thứ render chứ không phải thứ accept. Chúng ta generate view component thủ công hoặc qua component generator, nhưng không trước khi thêm gem vào Gemfile và chạy bundle install.

gem "view_component", require: "view_component/engine"

Để dùng generator, chạy:

rails generate component <Component name> <arguments needed for initialization>

Ví dụ, nếu muốn generate component hiển thị danh sách khóa học in-class trên nền tảng học tập, dùng lệnh:

rails g component Course course

Chúng ta truyền argument course vì sẽ initialize Ruby object này với course mong đợi hiển thị, và đặt tên Course vì nó render course. Trùng hợp!

Thành thạo ViewComponent: Hướng dẫn thực tế xây dựng View Components tái sử dụng trong Rails

Như thấy, component và view tương ứng tạo trong app/components, cùng file test.

ViewComponent bao gồm template generators cho erb, haml, và slim nhưng mặc định theo template engine trong config.generators.template_engine. Tuy nhiên, bạn có thể chỉ định template engine ưa thích:

rails generate component Course course --template-engine <your template engine>

Tiến hành tạo Course model và một số course hiển thị.

rails g model Course title:string price:decimal location:string
rails db:migrate

Trong console, nhanh tạo hai course:

Course.create(title: 'The Art of Learning', price: 125.00, location: 'Denmark')
Course.create(title: 'Organizing your Time', price: 55.00, location: 'London')

File course_component.rb generate với initialize method như sau.

Thành thạo ViewComponent: Hướng dẫn thực tế xây dựng View Components tái sử dụng trong Rails

Cần tạo course controller route đến danh sách courses.

rails g controller Courses index

Trong routes.rb, chỉ định root route:

root 'courses#index'

Bây giờ ready, bước tiếp theo tạo view. Làm trong course_component.html.erb đã generate.

<div>
  <h2><%= @course.title %></h2>
  <h4><%= number_to_currency(@course.price, :unit => "€") %></h4>
  <h4><%= @course.location %></h4>
</div>

Trong view, hiển thị title, price, location dùng biến @course, đã định nghĩa trong initialize method của CourseComponent. Tương tự khi tạo biến trong controller method, nó available trong view.

Biết controller hoạt động, route đến index.html.erb tương ứng của index method. Do đó, đây nơi render component.

#app/views/courses/index.html.erb
<%= render(CourseComponent.new(course: Course.find(1))) %>

Như trên, render instance mới CourseComponent bằng initialize với course muốn render trong view. Course này trở thành biến @course available cho course_component.html.erb.

Cũng có thể render component trực tiếp từ controller, bypass index view:

class CoursesController < ApplicationController
  def index
    render(CourseComponent.new(course: Course.find(1)))
  end
end

Bất kể method chọn, hiển thị trên server:

Thành thạo ViewComponent: Hướng dẫn thực tế xây dựng View Components tái sử dụng trong Rails

Nội dung bổ sung cũng có thể truyền vào component theo cách sau:

<%= render(CourseComponent.new(course: Course.find(1))) do %>
  container
<% end %>
<%= render(CourseComponent.new(course: Course.find(1)).with_content("container")) %>

Trong view component file, include content ở đâu muốn. Trong trường hợp, include như class bằng sửa div:

<div class=<%= content %>>

Tất cả method render additional content cho kết quả:

Thành thạo ViewComponent: Hướng dẫn thực tế xây dựng View Components tái sử dụng trong Rails

Render một Collection

Nếu muốn render toàn bộ danh sách courses? ViewComponent cung cấp cách thẳng tiến dùng tag with_collection. Thay vì initialize component bằng .new, initialize bằng .with_collection, và collection truyền như variable:

CourseComponent.with_collection(Course.all)

Cho kết quả:

Thành thạo ViewComponent: Hướng dẫn thực tế xây dựng View Components tái sử dụng trong Rails

Cũng có tag with_collection_parameter nếu muốn address collection bằng tên khác.

class CourseComponent < ViewComponent::Base
  with_collection_parameter :item
  def initialize(item:)
    @item = item
  end
end

Trong trường hợp, course parameter được address như item. Do đó, trong view tương ứng, @course thay bằng @item cho cùng kết quả.

Tham số bổ sung cũng có thể thêm vào collection. Các tham số hiển thị per item trong collection. Thêm text Buy Me cho mỗi item qua method này.

#app/views/courses/index.html.erb
<%= render(CourseComponent.with_collection(Course.all, notice: "Buy Me")) %>
# app/components/course_component.rb
class CourseComponent < ViewComponent::Base
  with_collection_parameter :item
  def initialize(item:, notice:)
    @item = item
    @notice = notice
  end
end

Thêm paragraph mới trong app/components/course_component.html.erb chỉ text cho notice variable mới.

<p><a href='#'> <%= @notice %> </a></p>

Cho kết quả:

Thành thạo ViewComponent: Hướng dẫn thực tế xây dựng View Components tái sử dụng trong Rails

Cuối cùng, dưới collections, có biến counter có thể bật để số thứ tự item trong view. Bật bằng thêm _counter vào collection parameter và làm available cho views qua initialize method.

#app/components/course_component.rb
def initialize(item:, notice:, item_counter:)
  @item = item
  @notice = notice
  @counter = item_counter
end

Trong views, bên cạnh item title, thêm counter:

<h2><%= @counter %>. <%= @item.title %></h2>

Tạo course thứ ba từ console hiểu rõ counter.

Course.create(title: 'Understanding Databases', price: '100', location: 'Amsterdam')

Cho kết quả:

Thành thạo ViewComponent: Hướng dẫn thực tế xây dựng View Components tái sử dụng trong Rails

Conditional Rendering

ViewComponent có hook render?, khi dùng xác định view có nên render. Triển khai bằng cho discount 10% cho courses giá >= 100 Euro. Tạo component cho mục đích này.

rails generate component Discount item

Thành thạo ViewComponent: Hướng dẫn thực tế xây dựng View Components tái sử dụng trong Rails

Component này tự động initialize với item nên hiển thị discount, như thấy dưới.

Thành thạo ViewComponent: Hướng dẫn thực tế xây dựng View Components tái sử dụng trong Rails

Do đó, trong discount_component.html.erb, thêm text muốn hiển thị.

<p class="green"> A 10% discount is available on this course </p>

Đừng ngần ngại thêm class green vào css file và gán màu green ưa thích. Thêm vào, trong discount_component.rb, thêm method render? xác định khi component render.

def render?
  @item.price >= 100
end

Bây giờ, render discount component trong view render mỗi course.

# app/components/course_component.html.erb
<%= render(DiscountComponent.new(item: @item)) %>

Cho kết quả:

Thành thạo ViewComponent: Hướng dẫn thực tế xây dựng View Components tái sử dụng trong Rails

Tuyệt vời không?

Helpers

Trong traditional Rails views, dễ plug helpers bằng gọi method name trong views, nhưng khác với view components. Trong view components, helper methods không gọi trực tiếp trong views nhưng có thể include trong component. Chúng ta đã có courses_helper.rb tự generate khi CoursesController tạo, tận dụng nó. Trước, tạo helper method cho biết bao nhiêu người enrolled course. Giá trị là quarter của price :).

module CoursesHelper
  def count_enrollees(course)
    count = (course.price / 4).round()
    tag.p "#{count} enrollees so far"
  end
end

Tiếp, tạo component gọi helper. Component này render trong view. Thêm statement include include helper, sau đó gọi bất kỳ method trong helper trong component này.

# app/components/enrollee_component.rb
class EnrolleeComponent < ViewComponent::Base
  include CoursesHelper
  def total_enrollees(course)
    count_enrollees(course)
  end
end

Bước cuối thêm EnrolleeComponent vào view hiển thị courses.

# app/components/course_component.html.erb
<%= EnrolleeComponent.new.total_enrollees(@item) %>

Lưu ý không dùng từ render cho EnrolleeComponent, vì nó không có view, output sẽ là helper method gọi. Cho kết quả:

Thành thạo ViewComponent: Hướng dẫn thực tế xây dựng View Components tái sử dụng trong Rails

Helpers dùng cho icons, gravitars, hoặc bất cứ gì. ViewComponent không thay đổi cách dùng helpers; chỉ thay đổi cách gọi trong components.

Phương thức before_render

ViewComponent cung cấp method before_render gọi trước khi component render. Thêm star cạnh discount notice. Bắt đầu thêm helper method lấy star; image star.png đã tải và đặt trong app/assets/images.

#app/helpers/courses_helper.rb
def star_icon
  image_tag("/assets/star.png", width: "1%")
end

Thêm method before_render vào Discount component gọi helper này.

# app/components/discount_component.rb
def before_render
  @star_icon = helpers.star_icon
end

Như thấy, cách khác gọi helpers: dùng helpers.method trong component.rb. Sau đó, trong render method DiscountComponent, input star icon, available qua @star_icon.

# app/components/discount_component.html.erb
<p class="green">
  <%= @star_icon %> A 10% discount is available on this course
</p>

Cho kết quả:

Thành thạo ViewComponent: Hướng dẫn thực tế xây dựng View Components tái sử dụng trong Rails

Không nhất thiết dùng helpers cho before_render. Dùng helpers để giới thiệu cách khác gọi helper methods.

Previews

Giống Action Mailer, ViewComponent cho phép preview components. Phải bật trước trong config/application.rb.

config.view_component.preview_paths << "#{Rails.root}/lib/component_previews"

Preview components nằm trong test/components/previews dùng preview component với nhiều input khác nhau. Preview DiscountComponent.

# test/components/previews/discount_component_preview.rb
class DiscountComponentPreview < ViewComponent::Preview
  def with_first_course
    render(DiscountComponent.new(item: Course.find(1)))
  end
  def with_second_course
    render(DiscountComponent.new(item: Course.find(2)))
  end
end

Hai method thêm preview DiscountComponent trong scenario khác. Xem tại https://localhost:3000/rails/view_components, tìm tất cả preview components và methods. Click vào bất kỳ cái nào xem trông như thế nào.

Thành thạo ViewComponent: Hướng dẫn thực tế xây dựng View Components tái sử dụng trong Rails

Như thấy trong video, course đầu render discount component, nhưng course hai không render. Bạn biết tại sao? Method render? check xảy ra. Scenario đầu giá > 100 euro (course 1), nhưng course 2 giá < 100 euro. Tên method không mô tả để bạn tự tìm ra trước khi highlight :).

Previews bật/tắt trong mọi environment dùng option show_previews, nhưng development và test environments bật mặc định.

# config/environments/test.rb
config.view_component.show_previews = false

JS VÀ CSS Inclusion

Có thể include JavaScript và CSS cùng components, đôi khi gọi "sidecar" assets hoặc files. Tính năng này vẫn experimental. Do đó, không đi sâu vào inner workings, nhưng tìm thêm về tính năng ViewComponent này tại đây.

Templates

Template của view component có thể định nghĩa nhiều cách. Option đơn giản: đặt view và component cùng folder, như dưới.

Thành thạo ViewComponent: Hướng dẫn thực tế xây dựng View Components tái sử dụng trong Rails

Như thấy, mọi component và view trong app/components.

Option khác: đặt view và assets khác trong subdirectory cùng tên component. Vì vậy, trong app/components, có file component.rb chứa component, và folder riêng course_component chứa view course_component.html.erb và assets khác liên quan.

Thành thạo ViewComponent: Hướng dẫn thực tế xây dựng View Components tái sử dụng trong Rails

Để generate component files cách này từ command line, cần flag --sidecar:

rails g component Example name --sidecar

Cho phép thêm css và js files vào component folder. ViewComponents cũng render không template file bằng định nghĩa method call. Ví dụ trong phần tiếp theo thảo luận slots.

Slots

Nhiều block content có thể truyền vào single ViewComponent dùng slots. Tương tự has_one và has_many trong Rails models, slots định nghĩa bằng renders_one và renders_many:

  • renders_one định nghĩa slot render tối đa một lần per component: renders_one :header.
  • renders_many định nghĩa slot render nhiều lần per-component: renders_many :titles.

Giả sử muốn page render header và titles tất cả courses available; đạt được dùng slots. Tạo ListComponent, chứa header render một lần, và TitleComponent, render nhiều titles.

#app/components/list_component.rb
class ListComponent < ViewComponent::Base
  renders_one :header, "HeaderComponent"
  # `HeaderComponent` định nghĩa trong component này, nên refer bằng string.
  renders_many :titles, TitleComponent
  # `titleComponent` định nghĩa file khác, nên refer bằng class name.
  class HeaderComponent < ViewComponent::Base
    def call
      content_tag :h1, content
    end
  end
end

Trong component, header render một lần, titles render nhiều lần, vì page chứa nhiều titles. Đã định nghĩa HeaderComponent trong ListComponent. Có thể làm vậy với ViewComponent; class định nghĩa trong class khác. Lưu ý method call thảo luận trước dưới Templates và cách dùng trong HeaderComponent render h1 tag, loại bỏ cần view file (html.erb). HTML file tương ứng ListComponent chứa:

#app/components/list_component.html.erb
<div>
  <%= header %>
  <!-- renders the header component -->
  <% titles.each do |title| %>
    <div>
      <%= title %>
      <!-- renders an individual course title -->
    </div>
  <% end %>
</div>

Trong html file, include header, iterate qua tất cả titles truyền vào component, render chúng. Như thấy, không cần chỉ định tên component render trong list view file; slots lo việc đó. Chỉ identify chúng như header và title.

Bước tiếp tạo TitleComponent và HTML file tương ứng, vì đây là thứ render cho mỗi title truyền.

# app/components/title_component.rb
class TitleComponent < ViewComponent::Base
  def initialize(title:)
    @title = title
  end
end
# app/components/title_component.html.erb
<div>
  <h3>
    <%= @title %>
  </h3>
</div>

Cuối, trong index.html, tạm xóa nội dung và thay bằng ListComponent render.

#app/views/courses/index.html.erb
<%= render ListComponent.new do |c| %>
  <% c.header do %>
    <%= link_to "List of Available Courses", root_path %>
  <% end %>
  <%= c.title(title: "First title") %>
  <%= c.title(title: "Second title!") %>
<% end %>

Thành thạo ViewComponent: Hướng dẫn thực tế xây dựng View Components tái sử dụng trong Rails

Bây giờ, truyền courses vào view như collection. Để truyền collection vào slot, truyền collection như array of objects chứa variable cần initialize. Như thấy, mỗi course truyền vào initialize với argument title. Có thể extract titles tất cả courses trong db thành array of hashes và render.

Thành thạo ViewComponent: Hướng dẫn thực tế xây dựng View Components tái sử dụng trong Rails

Thay list nhiều titles bằng single c.titles cho collection và truyền vào hash titles, định nghĩa bằng variable course_titles.

# app/views/courses/index.html.erb
<% course_titles = Course.all.pluck(:title).map { |title| {title: title}} %>
<% c.titles(course_titles) %>

Cho kết quả:

Thành thạo ViewComponent: Hướng dẫn thực tế xây dựng View Components tái sử dụng trong Rails

Đây chính là cách slots hoạt động: render nhiều components trong single ViewComponent. Slots render được nhiều cách khác, tìm thêm info tại đây.

Testing

Test view components bằng require "view_component/test_case" trong test file và dùng test helper render_inline để assertions trên rendered output. Bắt đầu test DiscountComponent.

require "test_helper"
require "view_component/test_case"
class DiscountComponentTest < ViewComponent::TestCase
  def test_render_component
    render_inline(DiscountComponent.new(item: "my item"))
  end
end

Chạy test bằng rails test test/components/discount_component_test.rb, nhận lỗi:

Thành thạo ViewComponent: Hướng dẫn thực tế xây dựng View Components tái sử dụng trong Rails

Chứng minh test đến đúng component nhưng thiếu prop phù hợp, vì item phải là course có price property không phải string. Nó cũng báo có method render? check trước render. Truyền variable đúng.

def test_render_component
  course = Course.create(title: 'Organizing your Time', price: 55.00, location: 'London')
  render_inline(DiscountComponent.new(item: course))
end

Chạy thành công. Thêm assertions.

def test_render_component
  course = Course.create(title: 'Organizing your Time', price: 155.00, location: 'London')
  render_inline(DiscountComponent.new(item: course))
  assert_selector 'p[class="green"]'
  assert_text "10% discount"
end

Test cũng pass. Nhớ có render condition cho component. Đừng lo, ViewComponent cũng cung cấp cách test component không render, dùng refute_component_rendered. Test với course giá < 100 euro.

def test_component_not_rendered
  course = Course.create(title: 'Organizing your Time', price: 55.00, location: 'London')
  render_inline(DiscountComponent.new(item: course))
  refute_component_rendered
end

Test cũng pass.

Viết test khác cho CourseComponent test render tất cả nested components.

require "test_helper"
require "view_component/test_case"
class CourseComponentTest < ViewComponent::TestCase
  def test_component_renders_all_children
    course = Course.create(title: 'Organizing your Time', price: 155.00, location: 'London')
    render_inline(CourseComponent.new(item: course, notice: 'A new test', item_counter: 1))
    assert_selector("h2", text: "Organizing your Time")
    assert_selector("h4", text: "€155.00")
    assert_selector("h4", text: "London")
    assert_text("enrollees")
    assert_text("discount")
  end
end

Test cũng pass. Test Enrollee và Discount components cũng render đúng.

Nhớ slot component, như hình dưới, render one header và many titles.

Thành thạo ViewComponent: Hướng dẫn thực tế xây dựng View Components tái sử dụng trong Rails

Để test, truyền component block code chứa header và titles nó nên render, sau đó assert trên rendered component.

require "test_helper"
require "view_component/test_case"
class ListComponentTest < ViewComponent::TestCase
  def test_renders_slots_with_content
    render_inline(ListComponent.new) do |component|
      component.header { "A Test List" }
      component.titles [{title: 'Test title 1'}, {title: 'Test title 2'}]
    end
    assert_selector("h1", text: "A Test List")
    assert_text("Test title 1")
    assert_text("Test title 2")
  end
end

Test cũng pass :).

Rspec Testing

Ngoài testing nói trên, nếu testing framework ưa thích là RSpec, cần cấu hình thêm để enable RSpec cho ViewComponents.

# spec/rails_helper.rb
require "view_component/test_helpers"
require "capybara/rspec"
RSpec.configure do |config|
  config.include ViewComponent::TestHelpers, type: :component
  config.include Capybara::RSpecMatchers, type: :component
end

Test DiscountComponent viết lại và test lại dùng RSpec:

require "rails_helper"
RSpec.describe DiscountComponent, type: :component do
  it "renders the component correctly" do
    course = Course.create(title: 'Organizing your Time', price: 155.00, location: 'London')
    render_inline(DiscountComponent.new(item: course))
    expect(rendered_component).to have_css "p[class='green']", text: "10% discount"
    expect(rendered_component).to have_css "img[src*='/assets/star.png']"
  end
end

Test pass elegantly. Hell yeah, thấy star icon.

Kết luận

Viết nhiều view components cho Rails app không chỉ làm code dễ đọc và ít lỗi từ complication không muốn mà còn cho phép test views isolated chứ không chỉ trong HTTP requests. View components dễ tích hợp vào Rails app hiện có, tốt nhất bắt đầu với views tái sử dụng nhiều. Với mọi thứ học được, đây là easy-peasy task. Tuy nhiên, nếu muốn thêm thông tin ViewComponent, đừng ngần ngại đọc documentation hoặc RubyDoc info.