You can use the built-in Rails cache to do this:
@history = Rails.cache.fetch('parsed_myservice_data', :expires_in => 1.minute) do JSON.parse connector.get_response("http://myservice") end
One of the problems with this approach is that recovering cached data takes quite a while. If during this time you receive many client requests, each of them will receive a missed cache and call your block, which will lead to a lot of duplicated efforts, not to mention the slow response time.
EDIT: In Rails 3.x, you can pass the :race_condition_ttl option to the fetch method to avoid this problem. Read more about it here .
A good solution for previous versions of Rails is to set the background / cron job, which should be run at regular intervals, which will retrieve and analyze data and update the cache.
In your controller or model:
@history = Rails.cache.fetch('parsed_myservice_data') do JSON.parse connector.get_response("http://myservice") end
In the background / cron job:
Rails.cache.write('parsed_myservice_data', JSON.parse connector.get_response("http://myservice"))
Thus, your client requests will always receive fresh cached data (except for the first request if the background / cron job is not already running.)
source share