0

I am using Draper to add decorators to several models, I have some decorators for one model (my documents model) that I want to use to "decorate" another model (my user model). How can I do this?

I have tried putting this in my documents decorator but it doesn't work.

decorates_association :user

**[decorators here]**

class UserDecorator < ApplicationDecorator
  decorates :user
end

and added this to my user controller:

def show
  @user = UserDecorator.find(params[:id])
end

Thankyou in advance!

Jeremy Lynch
  • 6,780
  • 3
  • 52
  • 63

2 Answers2

1

It looks like you've already got an ApplicationDecorator set up. If you have decorator methods that you want to share between models, you can include them in your ApplicationDecorator like this:

class ApplicationDecorator < Draper::Decorator
  def name
    model.name
  end

  def created
    model.created_at.strftime("%m/%d/%Y")
  end
end

And if you setup your UserDecorator and DocumentDecorator like this:

class UserDecorator < ApplicationDecorator
  delegate_all
end

class DocumentDecorator < ApplicationDecorator
  delegate_all
end

Then any of the decorator methods defined in ApplicationDecorator (name, created, etc.) will be available to decorated Users and decorated Documents.

We've got a couple of projects where we're using a similar setup to share decorator methods between multiple models for common attributes like date and time formatting, status, etc. Hope this helps.

QMFNP
  • 997
  • 8
  • 14
  • Is there some way to share, let us say, 3 methods between only 5 models, but do not share those methods with the rest of the models? Using `ApplicationDecorator` in this case is not applicable. Is there anything like `concern` for decorator? – kovpack Apr 12 '15 at 19:50
0

The other models which you would not like to share logic with could inherit directly from Draper::Decorator rather than from ApplicationDecorator. Only the 5 models should inherit from ApplicationDecorator

@kovpack

Van_Paitin
  • 3,678
  • 2
  • 22
  • 26