In my Rails application, I am trying to extract several exchange rates from an external service and store them in the cache:
require 'open-uri'
module ExchangeRate
def self.all
Rails.cache.fetch("exchange_rates", :expires_in => 24.hours) { load_all }
end
private
def self.load_all
hashes = {}
CURRENCIES.each do |currency|
begin
hash = JSON.parse(open(URI("http://api.fixer.io/latest?base=#{currency}")).read)
hashes[currency] = hash["rates"]
rescue Timeout::Error
puts "Timeout"
rescue OpenURI::Error => e
puts e.message
end
end
hashes
end
end
This works great in development, but the production environment bothers me. How can I prevent caching of all this if the external service is unavailable? How can I guarantee that it ExchangeRate.allalways contains data, even if it is old and cannot be updated due to an external service failure?
I tried to add basic error handling, but I'm afraid this is not enough.
source
share