I have a RoR 3.2.3
web site. It calls a web service of flickr.com
to get the list of my photos. But it doesn't really matter.
The bottom line is, that it does a request each time -- each time a visitor comes to my web site it calls a web service of flickr.com
to get the list of the photos. Obviously I'd like to cache the respose of flickr
for about 5 hours. As far as I'm concerned it would be enough.
So how can I do it? What is the good or best way to it or just the general approach? Maybe you have a link how to make it?
P.S. I use the free tariff plan of heroku.com
with 5Mb that supports PostgreSQL
database. However if it's necessary I could migrate to other hoster.
Memcached is a good option to start with. Heroku has it built-in for free (5mb). Setup guide can be found here
$ heroku addons:add memcache
$ vim Gemfile
gem 'dalli'
$ vim config/environments/production.rb
config.cache_store = :dalli_store
$ heroku console
Rails.cache.stats
Then you can wrap your expensive API request into Rails.cache block, see the code below:
class Flickr
def self.cached_request
Rails.cache.fetch "photos", :expires_in => 5.minutes do
flickr.photos.getRecent
end
end
end
Then to get use the cache, just run
Flickr.cached_request
It will fire API request and cache them for 5 minutes.
it depends on how you want your cache to work. usually, you are good with a memcached or redis store. both runs on heroku.
have a look at the guides for caching http://guides.rubyonrails.org/caching_with_rails.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With