Extend view with decorators

418 views Asked by At

I am using a ActiveJob object to generate a PDF with wicked_pdf. To do this I need to extend some view things to be able to do this is from a Job object:

view = ActionView::Base.new(ActionController::Base.view_paths, {})
view.extend(ApplicationHelper)
view.extend(Rails.application.routes.url_helpers)
view.extend(Rails.application.routes.url_helpers)

This is all working fine, the PDF is created. But in the view I use decorators like this:

- decorate invoice do |decorates|
  = decorates.title

And that is not working, probably because the object is not aware of these decorators, which are just PORO objects. So I guess I need to extend them too so they can be used here. How can I extend them? They are located in app\decorators

Edit: The decorates method comes from a helper method:

module ApplicationHelper
  def decorate(object, klass = nil)
    unless object.nil?
      klass ||= "#{object.class}Decorator".constantize
      decorator = klass.new(object, self)
      yield decorator if block_given?
      decorator
    end
  end
end

And that helper method loads the correct decorator object:

class InvoiceDecorator < BaseDecorator
  decorates :invoice
end

Which inherits from Base decorator:

class BaseDecorator
  def initialize(object, template)
    @object = object
    @template = template
  end

  def self.decorates(name)
    define_method(name) do
      @object
    end
  end
end
0

There are 0 answers