デコレーターの使い方
Draperを使用した際の使い方を説明します。
(railsでデコレーター層を使いたい時はDraperか、Active_Decoratorを使うのが一般的です)
①gemをインストールする
gem 'draper'
②bundle installする
$ bundle install
③以下のコマンドを実行する
$ rails generate draper:install
このコマンドを実行することでデコレーター層が追加される
④rails generate
で、対応させたいモデルのデコレーターを作成する
$ rails generate decorator ○○(モデル名)
⑤作成したデコレーターにメソッドを定義する
userモデルのデコレーターを作成した場合の例↓
class UserDecorator < Draper::Decorator delegate_all # delegate_allは、userモデルのメソッドを全て呼び出せるようにするためのもの def full_name "#{object.last_name} #{object.first_name}" # delegate_allが定義されていれば`object.`を省略することも可能 end end
⑥viewで使う
<%= decorate.full_name %>