lib类中的render_to_string不起作用

我正在尝试使用delayed_job通过xml更新远程数据库

在我的lib文件夹中,我放了一个带有一个类的文件,该类应该使用template.xml.builder执行render_to_text ,但是我得到:

 undefined method `render_to_string' for #... 

我究竟做错了什么?

 ac = ActionController::Base.new() ac.render_to_string(:partial => '/path/to/your/template', :locals => {:varable => somevarable}) 

我有一个未定义的辅助方法的问题,然后我使用ApplicationController

 ApplicationController.new.render_to_string 

render_to_stringActionController::Base定义。 由于类/模块是在Rails控制器范围之外定义的,因此该function不可用。

您将不得不手动渲染文件。 我不知道你用什么模板(ERB,Haml等)。 但是你将加载模板并自己解析它。

因此,如果ERB,这样的事情:

 require 'erb' x = 42 template = ERB.new <<-EOF The value of x is: <%= x %> EOF puts template.result(binding) 

您将必须打开模板文件并将内容发送到ERB.new ,但这个练习留给您。 以下是ERB的文档 。

这是一般的想法。

您可以将template.xml.builder转换为部分( _template.xml.builder ),然后通过实例化ActionView::Base并调用render

 av = ActionView::Base.new(Rails::Configuration.new.view_path) av.extend ApplicationController.master_helper_module xml = av.render :partial => 'something/template' 

我还没有用xml尝试过,但它适用于html partials。