Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get ISO currency code by country code in rails?

In my rails app I want to use country-code, currency-code, ISO locale code to fetch some data from API. How can I get this information dynamically when user visit my site from anywhere?

I have used geocoder gem so by request.location I will get location's information and using this gem I can get country-code. Now I am not getting how can I get remaining information such as currency-code & ISO locale code?? Can anyone please help me or guide me??

I have seen this money gem but not sure it will provide me all these information.

Thanks in advance :)

like image 481
Gagan Gami Avatar asked Dec 14 '25 07:12

Gagan Gami


2 Answers

I have tried @Prakash Murthy's answer. But there are many issue in this http://www.currency-iso.org/dam/downloads/table_a1.xml I found there is not proper name of all countries and some country has multiple currency_code which made me confused. But finally I found the solution by this single countries gem without creating any database.

Here is how I achieved the solution:

country_name = request.location.data['country_name'] # got country name
c = Country.find_country_by_name(country_name) # got currency details
currency_code = c.currency['code'] # got currency code

Sorry to answer my own question but I have posted here so in future if anyone stuck like me for the same issue then his/her time not wasted.

like image 195
Gagan Gami Avatar answered Dec 16 '25 21:12

Gagan Gami


I found a way that makes it really easy:

Add countries gem to Gemfile, then bundle install

def currency_for_country(currency_iso_code)

  ISO3166::Country.new(currency_iso_code).currency_code

end

Then:

currency_for_country('US')
=> "USD"

currency_for_country('AU')
=> "AUD"

This info is based off the countries gem readme

like image 43
stevec Avatar answered Dec 16 '25 22:12

stevec



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!