Loading 4 Votes - +

render_to_string in Rails Models or Rake Tasks

I recently ran into an issue with Rails that was preventing me from caching view content in my background rake tasks for a Rails app. There is a function available in the controller space called render_to_string that returns the rendered view template that I want to cache, but the problem is that I want to do my caching while not in the controller. The solution is easy, but not obvious.

# In a rake task:
av = ActionView::Base.new(Rails::Configuration.new.view_path)
Rails.cache.write(
  "cache_var", 
  av.render(
    :partial => "view_folder/some_partial", 
    :locals => {:a_var => @some_var}
  )
)

The magic is in the av variable that gives access to rendering your views. Once rendered, you can cache your view code like anything else.

Credit to Cory Patterson who led me in the right direction after hours of searching.

Similarly tagged OmniNerd content:

Thread parent sort order:
Thread verbosity:
-1 Vote  - +
Great post by Anonymous

Thx a lot, this is just what i was looking for.

The partial I want to cache uses various helper methods, and these are not included when you invoke ActionView explicitlly.. any hints as how to do that ?

0 Votes  - +
thankyou so much! by Anonymous

I’m trying to use ‘prawnto’ to render a pdf invoice and print it on the server whenever an invoice is completed. Sounds like a common task, but this your post seems to be the only thing on the net that has helped me so far! So thanks for sharing :)

0 Votes  - +
Rails 3.1 update by Anonymous

For those who get here thru Google and don’t know how to do the same in Rails 3.1.

I replaced:
av = ActionView::Base.new(Rails::Configuration.new.view_path)

With:
av = ActionView::Base.new(YOURAPP::Application.config.paths[“app/views”].first)

and thats it.

Share & Socialize

What is OmniNerd?

Omninerd_icon Welcome! OmniNerd's content is generated by nerds like you. Learn more.

Voting Booth

The most important factor in buying my next car is?

7 votes, 1 comment