Created
May 16, 2012 11:12
-
-
Save robotmay/2709589 to your computer and use it in GitHub Desktop.
Examples of low level caching
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
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
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 :)