lib/rack/geo_locale.rb in rack-geo-locale-0.0.4 vs lib/rack/geo_locale.rb in rack-geo-locale-0.0.5

- old
+ new

@@ -1,10 +1,15 @@ 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) @@ -44,23 +49,29 @@ {:language => language, :country => country, :q => q} end.sort {|x, y| y[:q] <=> x[:q]}.map{|o| [o[:language], o[:country]]}.first end def database? - if ENV["GEOIP_DATABASE"] - ::File.exist? ENV["GEOIP_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 - false + puts "WARNING: Set the ENV['GEOIP_DATABASE_URI'] to the location of your .gz database file." end end - def database - ENV["GEOIP_DATABASE"] - end - def geoip if database? - GeoIP.new(database) + GeoIP.new(DATABASE) else nil end end end