D-Nice
D-Nice

Reputation: 4870

Memcached for fragment cachine in Rails

I'm trying to figure out the best way to set organize the caching system for my scenario:

My web app has "trending movies," which are basically like twitter's trending topics -- the popular topics of conversation. I've written the function Movie.trending, which returns an array of 5 Movie objects. However, since calculating the trending movies is fairly CPU intensive and it will be shown on every page, I want to cache the result and let it expire after 5 minutes. Ideally, I'd like to be able to call Movie.trending from anywhere in the code and assume that cachine will work how i expect it to -- if the results are 5 minutes or earlier, then renew the results, otherwise, serve the cached results.

Is fragment caching the right selection for a task like this? Are there any additional gems I ought to be using? I'm not using Heroku.

Thanks!

Upvotes: 1

Views: 78

Answers (1)

Anatoly
Anatoly

Reputation: 15530

To reach this model's caching you can try Rails.cache.fetch, see the example below:

# model - app/models/movie.rb
class Movie
  def self.trending
    Rails.cache.fetch("trending_movies", :expires_in => 5.minutes) do
      # CPU intensive operations
    end
  end
end

# helper - app/views/helpers/application.rb
module ApplicationHelper
  def trending_movies
    content_tag :div do
      Movie.trending
    end
  end
end

# view - app/views/shared/_trending_movies
trending_movies

To test it in development mode don't forget to turn on caching for a specific environment

Upvotes: 1

Related Questions