lib/rack/geo_locale.rb in rack-geo-locale-0.0.8 vs lib/rack/geo_locale.rb in rack-geo-locale-0.0.10
- old
+ new
@@ -4,11 +4,11 @@
module Rack
class GeoLocale
DATABASE = "tmp/geoip_database.dat"
def initialize(app)
- fetch_database
+ @geoip = fetch_database
@app = app
end
def call(env)
@@ -28,28 +28,31 @@
end
private
def parse_country(env)
if database?
- if remote_addr = env["REMOTE_ADDR"]
- remote_addr = env["HTTP_X_FORWARDED_FOR"] if env["HTTP_X_FORWARDED_FOR"]
+ if addr = env["REMOTE_ADDR"]
+ addr = env["HTTP_X_FORWARDED_FOR"] if env["HTTP_X_FORWARDED_FOR"]
+ addr = addr.split(",").first.strip
- begin
- result = geoip.country(remote_addr).country_code2
- rescue Exception => e
- puts "WARNING: .country raised an exception #{e}"
- end
+ puts "INFO: Trying to lookup #{addr}"
- return result if result != "--"
+ result = @geoip.country(addr).country_code2
+
+ if result != "--"
+ puts "INFO: Found country for #{addr} #{result}"
+
+ result
+ else
+ puts "INFO: Didn't find country for #{addr}"
+ end
else
puts "WARNING: Didn't find env['REMOTE_ADDR']"
end
else
puts "WARNING: Didn't find geoip database."
end
-
- nil
end
def parse_locale(env)
env["HTTP_ACCEPT_LANGUAGE"] ||= ""
language_ranges = env["HTTP_ACCEPT_LANGUAGE"].split(",")
@@ -63,27 +66,23 @@
{:language => language, :country => country, :q => q}
end.sort {|x, y| y[:q] <=> x[:q]}.map{|o| [o[:language], o[:country]]}.first
end
def database?
- ::File.exist? DATABASE
+ @geoip != nil
end
def fetch_database
if ENV["GEOIP_DATABASE_URI"]
puts "-> Fetching #{ENV["GEOIP_DATABASE_URI"]}"
`curl --silent -o #{DATABASE}.gz #{ENV["GEOIP_DATABASE_URI"]}`
- `gunzip #{DATABASE}.gz`
- else
- puts "WARNING: Set the ENV['GEOIP_DATABASE_URI'] to the location of your .gz database file."
- end
- end
+ `gunzip -f #{DATABASE}.gz`
- def geoip
- if database?
GeoIP.new(DATABASE)
else
+ puts "WARNING: Set the ENV['GEOIP_DATABASE_URI'] to the location of your .gz database file."
+
nil
end
end
end
end