OmniNerd Article Propagation

Most Nerd-Its | Nerd Trends | Last Ten

  1. RE: Its evolutionary in Do you text while driving?
  2. RE: Agnostic nonsense… in Faith Kills Infant
  3. RE: Atheistic Nonsense in Faith Kills Infant
  4. President Obama Is No Friend To Gays in Gay Veteran Separated From Military
  5. RE: Poor Neda in Totalitarianism vs. Technology
  6. Pointless discussion in Faith Kills Infant
  7. RE: drive safe, have fun, stay connected in Do you text while driving?
  8. RE: No sir? in Gay Veteran Separated From Military
  9. Agnostic nonsense… in Faith Kills Infant
  10. RE: Atheistic Nonsense in Faith Kills Infant

What is OmniNerd?

Welcome! OmniNerd's content is generated by you, the reader. Through voting and moderation we strive to highlight the nerdiest of what's around and provide content that's a little more thought provoking than other sites.

Voting Booth

Do you text while driving?

48 votes, 10 comments
3
Nerd-Its
- +

render_to_string in Rails Models or Rake Tasks

Page_white_text

article by Mark A. McBride (markmcb) on 25 December 2008, tagged as render, rails, mvc, and ruby

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.