LoginSignup
56
57

More than 5 years have passed since last update.

よりよいView helperであるActiveDecoratorの使い方

Last updated at Posted at 2013-08-17

ActiveDecoratorを導入したきっかけ

  • Helperにグローバル関数っぽいメソッドを追加するのが嫌だ
  • Modelに表示に関するメソッドを増やすのが嫌だ

ActiveDecoratorのGemをいれる

gem 'active_decorator'

amatsuda/active_decorator
https://github.com/amatsuda/active_decorator

Decoratorファイルを作る

普通に作ってもいいですがgeneratorが用意されています。
rails g decorator user

/app/decorator/user.rbというファイルが作られます。このモジュールは自動でUserモデルにMix-inされます。(しかもViewのコンテキストの時だけ!)

公式にもあるサンプルです。姓と名を繋げてフルネームにするとか、linkのメソッドを追加したりしていますね。

# app/decorators/user_decorator.rb
module UserDecorator
  def full_name
    "#{first_name} #{last_name}"
  end

  def link
    link_to full_name, website
  end
end
56
57
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
56
57