LoginSignup
5

More than 5 years have passed since last update.

ActiveDecoratorでdecorateしたオブジェクトのhas_one/belong_to先のオブジェクトが自動でdecorateされるようにする

Last updated at Posted at 2015-03-23

シチュエーション

本来ならば、association先のオブジェクトの内容を描画する部分はpartialのtemplateに切り出すべきであろう、という思想のもとにactive_decoratorは作られていますが、それが難しい、あるいはやると逆に記述が煩雑になる場合があります。そういう場合の選択肢として。

実装

module AssociationDecorator
  def reader(*args)
    result = super
    if self.owner.is_a?(ActiveDecorator::Helpers)
      ActiveDecorator::Decorator.instance.decorate(result)
    end
    result
  end
end

module ActiveRecord
  module Associations
    class SingularAssociation
      prepend AssociationDecorator
    end
  end
end

今回はやってないですが、CollectionAssociationに同様にprependすることでhas_manyにも対応できるはずです。

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