require 'rake' namespace :geolocation do desc 'Update the Geolocation database. Specify target= to set the target.' task :update do require 'open-uri' require 'zlib' require 'stringio' raise 'Please specify the target' unless ENV['target'] file = ENV['target'] tmp_file = file + '.tmp' url = ENV['url'] || "http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz" content = nil open(url) do |io| compr = StringIO.new(raw = io.read) if compr.read(2) == "\x1f\x8b" compr.rewind gz = Zlib::GzipReader.new(compr) content = gz.read gz.close else content = raw end end begin File.open(tmp_file, 'w') do |f| f.write(content) end File.unlink(file) if FileTest.exists?(file) File.rename(tmp_file, file) rescue raise "Error: Problem updating file! #{$!} (#{$!.class})" end end end