Sha256: 93c569cfbcfed512f99da51fe37547e9141d61ae57818ba22cd978bf43cc5e97
Contents?: true
Size: 1.84 KB
Versions: 1
Compression:
Stored size: 1.84 KB
Contents
require 'geoip' require 'open-uri' module Rack class GeoLocale DATABASE = "tmp/geoip_database.dat" def initialize(app) fetch_database @app = app end def call(env) env["locale.language"], env["locale.country"] = parse_locale(env) if country = parse_country(env) env["locale.country"] = country end @app.call(env) end private def parse_country(env) if database? if remote_addr = env["REMOTE_ADDR"] result = geoip.country(remote_addr).country_code2 return result if result != "--" 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(",") language_ranges.map do |language_range| language_range += ';q=1.0' unless language_range =~ /;q=\d+\.\d+$/ locale, q = language_range.split(";q=") language, country = locale.strip.split("-") {: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 end def fetch_database if ENV["GEOIP_DATABASE_URI"] puts "-> Fetching #{ENV["GEOIP_DATABASE_URI"]}" open(ENV["GEOIP_DATABASE_URI"]) do |src| data = Zlib::GzipReader.new(StringIO.new(src.read)).read open(DATABASE, "wb") {|dst| dst.write(data)} end else puts "WARNING: Set the ENV['GEOIP_DATABASE_URI'] to the location of your .gz database file." end end def geoip if database? GeoIP.new(DATABASE) else nil end end end end
Version data entries
1 entries across 1 versions & 1 rubygems
Version | Path |
---|---|
rack-geo-locale-0.0.5 | lib/rack/geo_locale.rb |