Amit Patel
Amit Patel

Reputation: 15985

undefined method on decorated instance

Here is a decorator

app/decorators/campaign_decorator.rb

class CampaignDecorator < Draper::Decorator
  delegate_all Campaign::Campaign

  def created_at
    helpers.content_tag :span, class: 'time' do
      object.created_at.strftime("%a %m/%d/%y")
    end
  end

  def custom_method
    'hello there!'
  end
end

When I call CampaignDecorator.custom_method it doesn't find the method. Also CampaignDecorator.first.created_at returns unformated date.

Can anyone please tell what am I missing?

Upvotes: 2

Views: 3927

Answers (1)

xlembouras
xlembouras

Reputation: 8295

That is not how you use the Draper Decorator.

First things first:

  • CampaignDecorator.custom_method tries to find a class method called custom_method in the CampaignDecorator class. Which is definitely NOT what you want.

  • CampaignDecorator.first.created_at looks for objects of CampaignDecorator class and operates there ( where there are no records so first returns nil)

What you need to do is actually decorate your model. Check the documentation for that.

You first need to add the functionality to your model:

class CampaignDecorator
  decorates :campaign
end

In short you could do

@campaign = Campaign.first.decorate

@campaigns = CampaignDecorator.decorate_collection(Campaign.all)

@campaigns = Campaign.scoped.decorate

Upvotes: 5

Related Questions