0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

ActiveDecorator の手動デコレードが面倒なら

Posted at

ActiveDecorator は,たいがいのケースで自動的にデコレートしてくれるが,場合によってはあらわにデコレートを書かないといけないこともある。

具体的には,以下のように。
変数 @item に Item のインスタンスが入っているとき,これを ItemDecorator であらわにデコレートしてやるには,

ActiveDecorator::Decorator.instance.decorate(@item)

と書く。
しかし,これ,長ったらしいよね。
覚えられないから,毎回コピペしてこないといけないし。
めんどい。

これ,ApplicationRecord クラスのメソッドにしておけばいいんじゃね?

つまり,

app/models/application_record.rb
class ApplicationRecord < ActiveRecord::Base
  # 中略

  def decorate
    ActiveDecorator::Decorator.instance.decorate self
  end
end

みたいなのを用意しておく。
(Rails アプリを作ったら最初にこれを書く)

そしたら

@item.decorate

だけで済む。

ちなみに ActiveDecorator::Decorator.instance.decorate は引数を返り値にするので,

@item.decorate.hoge

みたいな感じでメソッドチェーンできる(この例で,hoge は ItemDecorator で定義したデコレーターメソッドのつもり)。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?