render_to_string in lib class not working

你。 提交于 2019-12-04 10:07:44

问题


I'm trying to use delayed_job to update a remote database via xml

In my lib folder I put a file with a class that should do a render_to_text with template.xml.builder, but I get:

undefined method `render_to_string' for #<SyncJob:0x7faf4e6c0480>...

What am I doing wrong?


回答1:


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



回答2:


I had problems with a undefined helper method then I used ApplicationController

ApplicationController.new.render_to_string



回答3:


render_to_string is defined in ActionController::Base. Since the class/module is defined outside the scope of the Rails controllers the function is not available.

You are going to have to manually render the file. I don't know what you are using for your templates (ERB, Haml, etc.). But you are going to have load the template and parse it yourself.

So if ERB, something like this:

require 'erb'

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

You will have to open the template file and send the contents to ERB.new, but that an exercise left for you. Here are the docs for ERB.

That's the general idea.




回答4:


You could turn your template.xml.builder into a partial (_template.xml.builder) and then render it by instantiating an ActionView::Base and calling render

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

I haven't tried it with xml yet, but it works well with html partials.




回答5:


Rails 5

render_to_string and others are now available as class methods on the controller. So you may do the following with whatever controller you prefer: ApplicationController.render_to_string

I specifically needed to assign a dynamic instance variable for the templates based on an object's class so my example looked like:

ApplicationController.render_to_string(
  assigns: { :"#{lowercase_class}" => document_object },
  inline: '' # or whatever templates you want to use
)

Great blog post by the developer who made the rails PR: https://evilmartians.com/chronicles/new-feature-in-rails-5-render-views-outside-of-actions



来源:https://stackoverflow.com/questions/2678045/render-to-string-in-lib-class-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!