Reputation: 13591
I have a new gem I'm playing with, but I'm not sure where to put it so that it is initialized, but that I don't have to do it each and every time I use my method which uses it.
def self.get_rate(from, to, amount)
Money.default_bank.fetch_rates #<---------------- Here it is...
if to == "USD" or from == "USD"
rate = Money.default_bank.get_rate(from, to) * amount
else
rate_to_us = Money.default_bank.get_rate(from, "USD") * amount
rate = Money.default_bank.get_rate("USD", to) * rate_to_us
#rate = Money.default_bank.get_rate(params[:currency][:from], "USD")
end
rate = Money.new(rate.to_money,to).format(:with_currency)
end
I have to initialize it once otherwise it won't work, but if I do it as it is now, it loads an xml file and whatever else. How can I do it so that it only loads once per day?
Upvotes: 1
Views: 1054
Reputation: 7474
The Money gem already supports fetching the exchange rate every so many seconds. You can put the code to set the auto-fetch in your require.rb file (RAILS_ROOT/config/initializers).
Money.default_bank.auto_fetch 86400
From the Money docs:
Money.default_bank.fetch_rates # Fetch the rates
Money.default_bank.auto_fetch 3600 # Fetch the rates every hour
Money.default_bank.stop_fetch # Stop auto-fetch
Upvotes: 2
Reputation: 6993
Put that logic into application.rb along with a check for the date and time. When the day changes, restart the initialization to update the exchange rates.
Upvotes: 0