Gagan Gami
Gagan Gami

Reputation: 10251

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 :)

Upvotes: 3

Views: 9673

Answers (3)

stevec
stevec

Reputation: 52358

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

Upvotes: 2

Gagan Gami
Gagan Gami

Reputation: 10251

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.

Upvotes: 7

Prakash Murthy
Prakash Murthy

Reputation: 13067

currency-code & ISO locale code are static data which change very rarely - if at all, and are best handled as static information within the system by storing them within the database tables. Might even be a good idea to provide a CRUD interface for managing these data.

One possible source for Currency code : http://www.currency-iso.org/en/home/tables/table-a1.html

List of All Locales and Their Short Codes? has details about getting the list of all locale codes.

Upvotes: 0

Related Questions