Skip to content

Instantly share code, notes, and snippets.

@mislav
Created September 3, 2012 11:48
Show Gist options
  • Select an option

  • Save mislav/3608766 to your computer and use it in GitHub Desktop.

Select an option

Save mislav/3608766 to your computer and use it in GitHub Desktop.

Revisions

  1. mislav created this gist Sep 3, 2012.
    43 changes: 43 additions & 0 deletions geoip_service.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,43 @@
    require 'faraday_middleware'
    require 'hashie/mash'

    # Public: GeoIP service using freegeoip.net
    #
    # See https://github.com/fiorix/freegeoip#readme
    #
    # Examples
    #
    # res = GeoipService.new.call '173.194.64.19'
    # res.country_code #=> US
    # res.city #=> Mountain View
    #
    # Returns a struct with the following fields:
    # - ip
    # - latitude, longitude
    # - city
    # - zipcode
    # - metrocode
    # - region_code, region_name
    # - country_code, country_name
    # - error (in case of HTTP error)
    class GeoipService
    def initialize http_adapter = nil
    @http_adapter = http_adapter || self.class.connection
    end

    def call ip_or_hostname
    @http_adapter.get(ip_or_hostname.to_s).body
    rescue Faraday::Error::ClientError => error
    Hashie::Mash.new :error => error
    end

    def self.connection
    @connection ||= Faraday.new 'http://freegeoip.net/json/' do |conn|
    conn.response :mashify
    conn.response :json
    conn.response :raise_error
    conn.adapter :net_http
    conn.options[:timeout] = 2
    end
    end
    end