Site cover image

fhhm’s blog

💎HelperとDecoratorの使い分け

Railsはたまにしか書かず、どうするんだっけとなることが多いので備忘メモ。

RailsのHelperDecorator(Draper)はどちらもプレゼンテーションロジックをまとめるものだが、特定のモデルに依存するロジックはDecoratorに、依存しないロジックはHelperに定義するのがよさそう。

  • Model
class User < ApplicationRecord
  # name:string, created_at:datetime, admin:boolean
end

  • View
<!-- app/views/users/show.html.erb -->
<p>名前: <%= @user.decorate.display_name %></p>
<p>登録日: <%= format_date(@user.created_at) %></p>

  • Decorator
    • 管理者の場合は専用のスタイルを適用するのはUserモデルに依存するプレゼンテーションロジックなのでDecoratorに定義
class UserDecorator < Draper::Decorator
  delegate_all

  def display_name
    if admin?
      h.content_tag(:span, "[Admin] #{name}", class: "admin-badge")
    else
      name
    end
  end
end

  • Helper
    • 特定のモデルに依存しない汎用的な日付フォーマットはHelperに定義
module ApplicationHelper
  def format_date(date)
    date.strftime("%Y/%m/%d")
  end
end