3 Nerd-Its - +

render_to_string in Rails Models or Rake Tasks

Page_white_text an academic article by Mark A. McBride (markmcb), published on 25 December 2008
tagged as render, rails, mvc, and ruby
other nerds have left 2 comments below

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.

Thread parent sort order:
Thread verbosity:
-1 Nerd-It - +
Great post by Anonymous :: NR0

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 ?

OmniNerd Article Propagation

The Showcase

Nerd-Its   Nerd Trends   Last Ten  

  1. RE: cell phones in How To Beat Traffic Mathematically
  2. RE: The true solution in Scientology: We've had it with you
  3. RE: Actually... in Scientology: We've had it with you
  4. RE: Actually... in Scientology: We've had it with you
  5. RE: The true solution in Scientology: We've had it with you
  6. RE: The true solution in Scientology: We've had it with you
  7. RE: Actually... in Scientology: We've had it with you
  8. RE: Actually... in Scientology: We've had it with you
  9. RE: The true solution in Scientology: We've had it with you
  10. RE: Actually... in Scientology: We've had it with you

What is OmniNerd?

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

Voting Booth

The Interstate Commerce Clause of the U.S. Constitution empowers Congress to regulate?

6 votes, 0 comments