Sha256: 16cdc86028e61f853e656ae83efac9a7409e184d21105ab6680244c22fb54688

Contents?: true

Size: 1.67 KB

Versions: 1

Compression:

Stored size: 1.67 KB

Contents

require "geoip"

module Geo
end

require "geo/instance"
require "expectation"

module Geo
  extend Instance
  
  # lookup the IP in the GeoLiteCity database on city level.
  def self.city(ip)
    # Use some global IP if we are running locally.
    if !ip || ip == "127.0.0.1"
      ip = "www.heise.de"
    end
    
    if city = instance.city(ip)
      complete_city(city)
    end
  end
  
  private

  def self.complete_city(city)
    city = city.to_hash

    parts = city.values_at :city_name, :region_name, :country_name
    city_name = parts.grep(/[a-zA-Z]/).join(", ")

    parts = city.values_at :continent_code, :country_code2, :region_name
    region_code = parts.grep(/[a-zA-Z]/).join(".")

    parts = city.values_at :continent_code, :country_code2
    country_code = parts.grep(/[a-zA-Z]/).join(".")

    city.update name: city_name, region_code: region_code, country_code: country_code
  end
  
  public
  
  def self.cities(s, &block)
    expect! s => [ Regexp, /../ ]
    
    s = Regexp.compile("^" + Regexp.escape(s) + "$") unless s.is_a?(Regexp)

    quietly do
      r = []

      instance.each.select do |rec|
        next if rec.city_name !~ s

        rec = complete_city(rec)
        yield rec if block
        r.push rec
      end

      r
    end
  end
  
  private
  
  # quietly and silence_stream are taken from activesupport

  def self.quietly
    silence_stream(STDOUT) do
      silence_stream(STDERR) do
        yield
      end
    end
  end

  def self.silence_stream(stream)
    old_stream = stream.dup
    stream.reopen(RbConfig::CONFIG['host_os'] =~ /mswin|mingw/ ? 'NUL:' : '/dev/null')
    stream.sync = true
    yield
  ensure
    stream.reopen(old_stream)
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
geo-lite-city-0.0.1 lib/geo.rb