Skip to content
This repository has been archived by the owner on Apr 10, 2018. It is now read-only.

Commit

Permalink
* added rails example to readme
Browse files Browse the repository at this point in the history
  • Loading branch information
Mihai Târnovan committed Jan 7, 2011
1 parent 6d98ed4 commit c5e1f6e
Showing 1 changed file with 41 additions and 1 deletion.
42 changes: 41 additions & 1 deletion README.markdown
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

Provides a minimalistic web service to map IPs to countries from a local MySQL database generated from data available from maxmind.com. Uses Sinatra and MySQL. Inspired by this article: http://jcole.us/blog/archives/2007/11/24/on-efficiently-geo-referencing-ips-with-maxmind-geoip-and-mysql-gis/

## Usage:
## Installation:

<pre>
gem i bundler
Expand All @@ -22,6 +22,46 @@ curl http://localhost:9292/country_code_from_ip/[some ip here]

Empty body and 404 response status means IP was not found in the database.

## Use it

A common use case might be detecting the user's language based on his location. In a Rails app you could setup a before_filter in your
application controller like this:

<pre>
...
before_filter :set_locale
...
def set_locale
if params[:locale]
I18n.locale = params[:locale]
else
res = geocode request.ip
if res.body.empty?
I18n.locale = Settings.default_locale
Rails.logger.warn "Geocoder found no match for #{request.ip}, falling back to default locale (#{Settings.default_locale})"
else
# implement a method to map countries to a language
I18n.locale = lang_from_country(res.body.downcase.to_sym)
end
end

# log the error, notify hoptoad, fallback to a default locale etc..
rescue Timeout::Error => ex
rescue Errno::ECONNREFUSED => ex
end
...
private
def geocode(ip)
url = URI.parse(Settings.geocoder.endpoint)
req = Net::HTTP::Get.new(url.path + ip)
Net::HTTP.new(url.host, url.port).start do |http|
http.read_timeout = Settings.geocoder.read_timeout
http.open_timeout = Settings.geocoder.open_timeout
http.request req
end
end
</pre>

## Why ?

* fast
Expand Down

0 comments on commit c5e1f6e

Please sign in to comment.