render_to_string in lib class not working

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.


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


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

ApplicationController.new.render_to_string

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