ViewComponentってなんやねん
- Rails 6.1 から標準で提供されるようになった
- Reactから影響を受けた、Presenter(ViewのためのUIのビジネスロジックを書く)パターンの進化版
- viewの再利用性を向上させるためのコンポーネントベースのアプローチ
パーシャルと何が違うの?
-
ViewComponent はパーシャルよりも独立したユニットとして扱われるため、コンポーネントごとにテストを書くことが簡単にできる
-
パーシャルより読み込みが早い = パフォーマンスが向上する
従来のRailsテンプレートは実行時に読み込まれていたが、ViewComponentのテンプレートは、アプリケーション起動時にプリコンパイルされるため -
コードの品質が高まる
ViewComponentは単なるRubyのオブジェクトのため、コードの品質基準を守ることが比較的に容易
使い方
gemをインストール
gem "view_component"
基本的にrb
ファイルとerb
ファイルがセットで生成される。
rails g component コンポーネント名 引数
---
app/components/
├── コンポーネント名_component.html.erb
└── コンポーネント名_component.rb
例としてはこんな感じ。
# app/components/example_component.rb
class ExampleComponent < ViewComponent::Base
def initialize(title:)
@title = title
end
end
<%# app/components/example_component.html.erb %>
<span title="<%= @title %>"><%= content %></span>
# 呼び出し元
<%= render(ExampleComponent.new(title: 'my title')) do %>
Hello, World!
<% end %>
<!--出力結果-->
<span title="my title">Hello, World!</span>
app/components/example_component.rb
だけでも表示することはできる
class ExampleComponent < ViewComponent::Base
def initialize(url:)
@url = url
end
def call
button_to('削除', @url, method: :delete)
end
end
<%= render ExampleComponent.new(url: xxxx_path) %>
ViewComponentではクラス内でcall
メソッドを定義し、その中でビューをレンダリングするためのロジックが書かれてあるので、そこに表示したい内容を書くこともできる。