我正在使用ActiveJob对象使用wicked_pdf生成PDF。要做到这一点,我需要扩展一些视图,以便能够从Job对象中执行此操作:
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)
这一切都正常,PDF已创建。但在视图中我使用这样的装饰器:
- decorate invoice do |decorates|
= decorates.title
这不起作用,可能是因为对象不知道这些装饰器,它们只是PORO对象。所以我想我也需要扩展它们以便在这里使用它们。我怎样才能延长它们?它们位于app\decorators
编辑:
decorates
方法来自辅助方法:
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
该辅助方法加载正确的装饰器对象:
class InvoiceDecorator < BaseDecorator
decorates :invoice
end
继承自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