active_decoratorも使ってみた

前回の記事でdraperを使ってview側のロジックを減らすというのを書きましたが、今回はactive_decoratorです。

設定の仕方は簡単です。
Gemfileにまずは追加してbundle installを実行してインストールします。


gem 'active_decorator'

$ bbundle install --path vendor/bundle

続いてactive_decoratorのジェネレータを実行してファイルを生成します。


bundle exec rails g decorator [該当するmodel名]

生成されたものは次のようになります。userモデル二対するactive_decoratorのソースです。

# coding: utf-8
module UserDecorator
end

これにuser.nameの最初の6文字まで表示するshort_nameを追加します。

# coding: utf-8
module UserDecorator
  def short_name
    name[0..5]
  end
end

では、これを実際に使ってみます。
詳細画面と一覧画面それぞれについてコードは以下の通りです。

詳細表示は

<p id="notice"><%= notice %></p>

<p>
  <strong>Name:</strong>
  <%= @user.name %>(<%=@user.short_name %>)
</p>

<p>
  <strong>Age:</strong>
  <%= @user.age %>
</p>

<p>
  <strong>Description:</strong>
  <%= @user.description %>
</p>

<%= link_to 'Edit', edit_user_path(@user) %> |
<%= link_to 'Back', users_path %>

一覧表示では

<h1>Listing users</h1>

<table>
  <thead>
    <tr>
      <th>Name</th>
      <th>Age</th>
      <th>Description</th>
      <th colspan="3"></th>
    </tr>
  </thead>

  <tbody>
    <% @users.each do |user| %>
      <tr>
        <td><%= user.name %>(<%= user.short_name %>)</td>
        <td><%= user.age %></td>
        <td><%= user.description %></td>
        <td><%= link_to 'Show', user %></td>
        <td><%= link_to 'Edit', edit_user_path(user) %></td>
        <td><%= link_to 'Destroy', user, method: :delete, data: { confirm: 'Are you sure?' } %></td>
      </tr>
    <% end %>
  </tbody>
</table>

<br>

<%= link_to 'New User', new_user_path %>

draperでは一覧表示を実現するためにコードの追加など必要でしたが、active_decoratorはシンプルですね。
まだdraperで作成した~Decoratorとactive_decoratorで作成した~Decoratorとではクラス継承関係も大分違います
まずdraperの場合は

[UserDecorator,
 Draper::AutomaticDelegation,
 Draper::Decorator,
 ActiveModel::Serializers::Xml,
 ActiveModel::Serializers::JSON,
 ActiveModel::Serialization,
 Draper::ViewHelpers,
 Object,
 ActiveSupport::Dependencies::Loadable,
 PP::ObjectMixin,
 JSON::Ext::Generator::GeneratorMethods::Object,
 Kernel,
 BasicObject]

です。で、active_decoratorの場合はこうなります(何か変な気がするな・・・・)。

[UserDecorator]

私の感覚なのですが、シンプルで使い易いのはactive_decoratorでした。
皆様はどうでしょうか?