我正在尝试呈现一个.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 %>
present
由ApplicationHelper
和ConfigurationPresenter
提供。{/ p>
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
。
使助手和演示者都可用并传入变量的正确方法是什么?