Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
=begin
host_ip_info.rb (http://gist.github.com/169374)
Copyright (c) 2009 Jason L Perry
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
=end
require "net/http"
require "yaml"
# A thin wrapper for the hostip.info API
class HostIPInfo
# Request geolocation for the given IP address.
def self.[] ip
begin
timeout(2) { @response = Net::HTTP.get_response("api.hostip.info", "/get_html.php?ip=#{ip}&position=true") }
Response.new *YAML::load(@response.body).values_at("City", "Country", "Latitude", "Longitude")
rescue Timeout::Error
Response.new
end
end
class Response < Struct.new(:city, :country, :latitude, :longitude)
def to_hash
Hash[*members.zip(values).flatten]
end
end
end
if $0 == __FILE__
require "test/unit"
require "rubygems"
require "mocha"
class HostIPInfoTest < Test::Unit::TestCase
def setup
@http_mock = mock('Net::HTTPResponse')
@http_mock.stubs :code => "200",
:message => "OK",
:content_type => "text/html",
:body => "Country: UNITED STATES (US)\nCity: St. Petersburg, FL\nLatitude: 27.758\nLongitude: -82.6421"
Net::HTTP.stubs(:get_response).returns(@http_mock)
end
def test_city
assert_equal "St. Petersburg, FL", HostIPInfo["127.0.0.1"].city
end
def test_country
assert_equal "UNITED STATES (US)", HostIPInfo["127.0.0.1"].country
end
def test_latitude
assert_equal 27.758, HostIPInfo["127.0.0.1"].latitude
end
def test_longitude
assert_equal -82.6421, HostIPInfo["127.0.0.1"].longitude
end
def test_to_hash
hash = {
"city" => "St. Petersburg, FL",
"country" => "UNITED STATES (US)",
"latitude" => 27.758,
"longitude" => -82.6421
}
assert_equal hash, HostIPInfo["127.0.0.1"].to_hash
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment