1

我正在尝试渲染一个.txt.erb使用演示者来显示值的文件。以下代码在ConfigurationWorker其中由 resque 执行:

@configuration = Configuration.first
@view = Rails.root.join 'lib', 'templates', 'config.txt.erb' 
ERB.new(File.read(@view)).result(binding)

config.txt.erb看起来像这样(为简单起见缩短):

<% present @configuration do |presenter| %>
  Name <%= presenter.name %>
<% end %>

presentApplicationHelper和提供ConfigurationPresenter

module ApplicationHelper
  def present(object, klass = nil)
    klass ||= "#{object.class}Presenter".constantize
    presenter = klass.new(object, self)

    yield presenter if block_given?
    return presenter
  end
end

class ConfigurationPresenter < ApplicationPresenter
  presents :configuration
  delegate :name, :configuration

  # Presenter methods omitted
end

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

  def self.presents(name)
    define_method(name) do
      @object
    end
  end

  def method_missing(*args, &block)
    @template.send(*args, &block)
  end
end

但是,这会导致NoMethodError: undefined method present for ConfigurationWorker:Class.

我还尝试了其他方法,例如

@configuration = Configuration.first
renderer = ApplicationController.view_context_class.new
renderer.render :file => Rails.root.join('lib', 'templates', 'config.txt.erb')

这导致ActionView::Template::Error: uninitialized constant NilClassPresenter.

使助手和演示者都可用并传入变量的正确方法是什么?

4

0 回答 0