LoginSignup
0
0

More than 3 years have passed since last update.

RailsでPresenterを有効活用する

Last updated at Posted at 2019-09-11

記事の目的

  • Presenterというロジックを自分なりに使い方をまとめて行く。
  • Presenterを以下のように定義する。

特定のビューを表示するのに必要なデータをパラメーターにした、巨大なJSONオブジェクトのようなもの

  • これがあると、Presenterに引数を渡すだけで
    • 「そのビュー内でどの情報が呼び出されているのか」が一目でわかり、
    • 「ビューが正常に表示されること」を保証しやすくなる
  • なおDecoratorとの違いは、PresenterはDecoratorの上位レベルに属し、必要に応じてPresenterからDecoratorに処理をdelegateすることがある。(サンプル参照)
  • 基本的にはPresenterだけ作り、複数箇所で使いまわしたい処理をDecoratorに記載する。

Presenterの原則

  • 「情報」を返すメソッドしか生やさない。(タグやActionViewヘルパーを返すメソッドは生やさない)
  • delegateで極力賄い、データの加工が必要な場合だけメソッドを生やす。
  • 情報によって見た目を変えることを実現したい場合は、クラス名を返すメソッドを生やして、HTMLのclass属性内で呼び出す。

サンプル

  • 「飼い犬の詳細ページ」をレンダーする場合を考える。
class DogShowPresenter
  attr_reader :dog

  delegate :name,
           to: :dog

  def initialize(current_user:, dog:)
    @dog = dog
    # もしデコレーターを使うならここでデコレーターを呼び出す
    # @dog = ActiveDecorator::Decorator.instance.decorate(dog)
  end

  def something
    # このPresenterでしか使わない処理を書く
  end
end

参考URL

https://tech.kitchhike.com/entry/2018/02/28/221159
https://www.oiax.jp/rails/tips/decorators_and_presenters.html

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