Search code examples
ruby-on-railsrubyruby-on-rails-3cachingfragment-caching

Populate cache in Rails manually


In Rails 3.x I want to precompile my cache manually, and I use fragment caching in the views on model instances and static HTML.

Rails lazily populates the cache when the page is requested, which results in a slow loading time on first load.

So given this sample code:

  <% cache("index_chart") do %>
    <%= high_chart("chart", @h) %>  
  <% end %>

How can I manually populate the cache with Ruby?


Solution

  • Probably the simplest method is to write a shell script that issues GET requests to various URLs that will cover your caches, otherwise known as cache warming.

    A simple setup would be creating a shell script called scripts/cache_warmer in your application, then you can trigger it manually from your servers command line, from your deploy script, or from a background processor like resque.

    # Sample scripts/cache_warmer
    
    GET http://localhost/
    GET http://localhost/some_other_page
    

    An alternative if you wanted it to be a bit more intelligent. Such as being able to hit member urls for a resource would be to use a rake task.

    # lib/tasks/cache_warmer.rake
    
    task :cache_warmer => :environment do
      Resource.all.each do |resource|
        Net::HTTP.get_response("http://localhost/resources/#{resource.id}")
      end
    end
    

    This of course is just a basic example. Your actual code would vary depending on the routes your trying to hit and how many there are. You may want to look at options to multithread for higher concurrency, or using an alternate 'worker' server to perform the requests from. The sky's the limit in terms of how complex this can get, just depends on your setup.