Reputation: 1755
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?
Upvotes: 24
Views: 20110
Reputation: 1937
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
Upvotes: 3
Reputation: 179
I had problems with a undefined helper method then I used ApplicationController
ApplicationController.new.render_to_string
Upvotes: 8
Reputation: 644
ac = ActionController::Base.new()
ac.render_to_string(:partial => '/path/to/your/template', :locals => {:varable => somevarable})
Upvotes: 62
Reputation: 240
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.
Upvotes: 2
Reputation: 5101
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.
Upvotes: 3