Kyle Decot
Kyle Decot

Reputation: 20835

Fragment Caching In Rails 3

I have a partial that pulls in weather data using the Barometer gem. The problem is that each time the page is loaded the gem is pulling in the weather feed again. Is it possible to cache the partial using fragment caching but only have that cached version to be good for say 3-4 hours? That way the weather data will stay current and the gem won't have to pull in brand new data each time.

Upvotes: 1

Views: 2134

Answers (1)

jesse reiss
jesse reiss

Reputation: 4579

the cache helper function takes 3 arguments :

  def cache(name = {}, options = nil, &block)
    if controller.perform_caching
      safe_concat(fragment_for(name, options, &block))
    else
      yield
    end

    nil
  end

if you provide an expiration key in the second argument it will be passed on to write_fragment and eventually the cache itself.

Like this :

-cache "cache_path", :expires => 3.hours do
  =cached_fragment_code

I recommend reading into ActionView::Helpers::CacheHelper for more info.

Upvotes: 6

Related Questions