LoginSignup
5
1

More than 3 years have passed since last update.

rails6.1から追加される予定のActionView::Componentを4ステップで入門

Last updated at Posted at 2019-12-23

rails6.1から追加される予定のActionView::Componentを4ステップで入門

準備

事前にサンプルrailsアプリケーションを作成しておきます。

$ rails new try_action_view_compponent
$ cd try_action_view_compponent
$ rails g scaffold user
$ rails db:create
$ rails db:migrate

"actionview-component"の基本的な使い方

1. Gemfileにgem "actionview-component"を追加

Gemfile
+ gem "actionview-component"
bundle install

2. config/application.rbでモジュールをrequireする

config/application.rb
+ require "action_view/component/railtie"

3. componentをgenerate

$ rails g component User name

作成された以下のファイルがコンポーネントファイルです。

app/component/user_component.html.erb
app/component/user_component.rb

使いやすくするために編集します。
ここでは、classと要素を外部注入するコンポーネントにします。

app/components/user_component.html.erb
- <div>Add User template here</div>
+ <span class="<%= name %>">
+   <%= content %>
+ </span> 
app/components/user_component.rb
class UserComponent < ActionView::Component::Base
+ attr_reader :name

  def initialize(name:)
    @name = name
  end
end

4. viewからコンポーネントを呼び出す

事前準備でscaffoldコマンドで作成しておいたusersのviewsから呼び出してみます。

app/views/users/index.html.erb
<h1>Users</h1>

+ <%= render(UserComponent, name: "test name") do %>
+   Hello, World!
+ <% end %>

rails sして画面からlocalhost:port/usersにアクセスすると呼び出したコンポーネントが表示される事が確認できます。

renderについて

renderメソッドの第一引数にコンポーネントのクラス名を第二引数に変数のキーワード引数を渡します。
ブロックの中に記述した文字列が、コンポーネント内でcontent変数を使用する事で呼び出す事ができます。

その他

バリデーション

modelのvalidationの様にコンポーネントに注入される変数の入力チェックがあるので試してみましょう。

バリデーション宣言を追加します。
ここではname変数は入力必須にします。

app/components/user_component.rb
class UserComponent < ActionView::Component::Base
  attr_reader :name

+ validates :name, presence: true

viewから呼び出す時にnameに空文字を渡してみます。

app/views/users/index.html.erb
<h1>Users</h1>

- <%= render(UserComponent, name: "test name") do %>
+ <%= render(UserComponent, name: "") do %>
+   Hello, World!
+ <% end %>

rails sして、localhost:port/usersにアクセスすると以下のエラーが表示される事が確認できます。

ActiveModel::ValidationError in Users#index
Validation failed: Name can't be blank

CSSファイル

以下の様にサイドカーCSSを配置するのがベストプラクティスの様です。

- /app
  - /components
    - /alert
      - alert.css
      - alert.html.erb
      - alert.rb

See: https://github.com/github/actionview-component/issues/55

動作環境

$ rails -v
Rails 6.0.2.1
$ ruby -v
ruby 2.6.4p104 (2019-08-28 revision 67798) [x86_64-darwin17]

サンプルコード

5
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
1