How to get the exchange currency exchange rate in rails?

2.7k views Asked by At

I tried to get the exchange rate like this in my Rails app :

1.to_money.exchange_to('USD')

(Note : I have set the default currency to my local currency which is lkr). This returns 0. Im using the money-rails gem.

3

There are 3 answers

0
THpubs On BEST ANSWER

The answer can be found from the link @aurelius have posted. Without using exchange_to, there's a direct way to get just the exchange rate. Since I use google currency gem and have configured it as the default_bank in the initializer, I can get the rate like this :

MoneyRails.default_bank.get_rate(:LKR, :USD)
0
Rameez On

I found the solution on the CurrencyFreaks API. You can also change the 'base' currency and get the response for the specific currencies. For base=SEK, you can get the SEK to USD exchange rate thru this code:

require "uri"
require "net/http"

url = URI("https://api.currencyfreaks.com/latest
    ?apikey=YOUR_APIKEY
    &base=SEK
    &symbols=USD")

https = Net::HTTP.new(url.host, url.port);
https.use_ssl = true

request = Net::HTTP::Get.new(url)

response = https.request(request)
puts response.read_body

I hope, it will work for you too.

1
aurelius On

have you tried this:

bank.get_rate(:LKR, :USD).to_f