So building my little web app (An Arabic tool to convert Arabic numbers to their text representation), I needed to detect user’s country to improve the site usability by improving the defaults.
researching, found this to be the simplest way possible. It does not
even require a database. As you will be connecting to third party
– Create an account at IPInfoDB.com
– Once you register, you will get your api key.
– Download geo-ip Ruby Gem (gem has not been updated since March 2012, but it is still working like a charm with even with latest Rails 4)
– Now, all you need to do is to create an initializer file in the folder config/initializers (call it geo-ip):
GeoIp.api_key = ‘YOUR_API_KEY’
– Then you can get the ip of the user by this rails method:
user_ip = request.remote_ip
– From the received ip, you can now get location info of users by calling methods of the geo-ip gem:
country = GeoIp.geolocation(user_ip, :precision => :country)
For all geo ip methods, please the check out the gem documentation