LoginSignup
1
2

More than 5 years have passed since last update.

RailsでDraperを使ってdecoratorを実装してみる

Posted at

苦手意識が強かったDecoratorについて調べた

decoratorとは

デザインパターンの一つ。既存のオブジェクトをdecorator層でラップすることで、機能を追加したり拡張したりできる。既存のオブジェクトに対して、何らかの実装をしたい場合、これを使えば、ビューファイルにロジックを記述せずにすむ

Draperとは何か

DraperはRailsのプレゼンテーション層(viewとモデルの中間にある)の役割を担うgem

decoratorとhelperとの違い

Decorator => 特定のモデルに関連した描画ロジックを実装
helper => モデルから独立し直接関係していない描画ロジックを実装
※helperのメソッドはグローバル空間で定義されるので、名前の重複なども起こりやすい

使い方

Draperをinstall

gemfile
gem 'draper'
bundle install

decoratorファイルを作成

item_decorator.rb
class ItemDecorator < Draper::Decorator
  delegate_all

  def has_hashtag?
    object.hashtag.present?
  end

controllerでオブジェクトをデコレートする

item_controller.rb
@items = ItemDecorator.decorate_collection(Item.all)

# decorate_collection
コレクションの個々のオブジェクトをデコレートする
# decorate
単独のオブジェクトをデコレートする

Viewで呼び出し

index.html.erb
<% @items.each do |item| %>
  <% if item.has_hashtag? %>
    <%= item.hashtag %>
  <% else %>
    <%= item.type %>
  <% end %>
<% end %> 

いまいちうまいユースケースを載せられなかった..

1
2
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
1
2