Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Caching calls to an external API in a rails app

The rails app (4) calls an external API using HTTParty. The API is read only. Caching is required as the data does not change often (24h) and the API allow only a limited number of calls per hour.

I guess I need some kind of hash based cache where I will use "params/sent/to/the/api" as key. Rails tools for caching seems only to be for pages,fragments or SQL.

What should I do to cache calls to an external API?

like image 944
Syl Avatar asked Nov 06 '13 18:11

Syl


1 Answers

It'll be something like this. Basically, the Rails.cache.fetch call will wrap your API call. It won't hit the API unless the cache has expired.

class Results

  def get(url, params)
    Rails.cache.fetch([url, params], :expires => 1.hour) do
      HTTParty.get('url/to/api')
    end
  end

end

Be sure you have a cache set in your environment. Memcache works great for this sort of thing.

like image 155
Mark Swardstrom Avatar answered Sep 19 '22 01:09

Mark Swardstrom