Skip to content

Instantly share code, notes, and snippets.

@robotmay
Created May 16, 2012 11:12
Show Gist options
  • Save robotmay/2709589 to your computer and use it in GitHub Desktop.
Save robotmay/2709589 to your computer and use it in GitHub Desktop.
Examples of low level caching
class ApplicationController < ActionController::Base
protect_from_forgery
before_filter do
@categories = Rails.cache.fetch("global/categories", expires_in: 10.minutes) do
Category.where("posts_count > 0").all
end
end
end
class Place < ActiveRecord::Base
def flickr_place
flickr = FlickRaw::Flickr.new
@flickr_place ||= Rails.cache.fetch("places/#{self.id}-#{self.updated_at}/flickr/place_id", expires_in: 7.days) do
unless self.latitude.blank? || self.longitude.blank?
begin
places = flickr.places.findByLatLon(lat: self.latitude, lon: self.longitude)
if places.blank?
nil
else
places.first
end
rescue Exception => e
logger.info "Exception occurred fetching Flickr place ID: #{e.to_s}"
nil
end
end
end
end
end
@r38y
Copy link

r38y commented May 17, 2012

Hey, nice demonstration of lower-level caching! Some of the ruby code was bugging me so I forked it and make some tweaks. Hopefully they are helpful and not rage-inducing :)

@robotmay
Copy link
Author

Awesome, thanks Randy!
I'd made a few of those tweaks on my local code already after someone pointed them out yesterday, but I hadn't thought of using .try; I'm going to use that myself now, as it's quite a bit neater :D

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment