Detecting User Location with Rails

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.

After
researching, found this to be the simplest way possible. It does not
even require a database. As you will be connecting to third party
database.

– 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

Google Map Marker

Google Map Marker (Photo credit: [ Mooi ])

Advertisements

Get Rubied Before Getting Railed

Don’t jump into learning Ruby on Rails. I can’t wait for that too. But I already know that a good Ruby on Rails developer is a good Ruby programmer.

Let’s get Rubied before getting Railed.

I think we will love Ruby