Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails - how to cache the result of a response of an API service?

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.

like image 376
Alexandre Avatar asked Dec 07 '22 13:12

Alexandre


2 Answers

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.

like image 161
Anatoly Avatar answered Apr 13 '23 01:04

Anatoly


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

like image 22
phoet Avatar answered Apr 12 '23 23:04

phoet