Skip to content

Commit

Permalink
refactoring class methods
Browse files Browse the repository at this point in the history
  • Loading branch information
thoughtpunch committed Jan 11, 2012
1 parent a142892 commit b9107cf
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 27 deletions.
61 changes: 35 additions & 26 deletions lib/geolocater.rb
Expand Up @@ -4,35 +4,44 @@

class Geolocater

def self.ip_lookup(ip_address)

#IP Regex check
if /\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b/.match(ip_address).nil?
raise "Not a valid IPv4 address"
#Localhost Check
elsif ip_address == "127.0.0.1"
raise "Can't lookup localhost addresse. Please use an external IP address!"
else
#THIS IS THERE THE CODE EVAL WILL GO
Geolocater.geolocate_ip(ip_address)
end
end

private
def self.geolocate_ip ip_address
uri = "http://freegeoip.net/json/#{ip_address}"
http_response = Faraday.get uri
if http_response.success? == true && http_response.status == 200;
#JSON PARSE THE BODY
result = JSON.parse(http_response.body)
if result["city"].empty?
raise "Incomplete record. Please try another address"
class << self

def ip_lookup(ip_address)
#IP Regex check
if /\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b/.match(ip_address).nil?
raise "Not a valid IPv4 address"
#Localhost Check
elsif ip_address == "127.0.0.1"
raise "Can't lookup localhost address. Please use an external IP address!"
#If valid, pass the ip address to the 'geolocate' method
else
return result
geolocate_ip ip_address
end
else
raise "IP address not found"
end

private
def geolocate_ip ip_address
#the request URI
uri = "http://freegeoip.net/json/#{ip_address}"
#Get the response with Faraday and store to 'http_response' var
http_response = Faraday.get uri
#If the HTTP request is successful...
if http_response.success? == true && http_response.status == 200;
#JSON PARSE THE BODY
result = JSON.parse(http_response.body)
#If the response is missing basic info, like 'city'...
if result["city"].empty?
raise "Incomplete record. Please try another address"
#otherwise return the result
else
return result
end
#If the HTTP request fails...
else
raise "IP address not found"
end
end

end

end
2 changes: 1 addition & 1 deletion spec/geolocater_spec.rb
Expand Up @@ -21,7 +21,7 @@
end

it "should not accept localhost/loopback address" do
expect {Geolocater.ip_lookup("127.0.0.1")}.to raise_error(RuntimeError,"Can't lookup localhost addresse. Please use an external IP address!")
expect {Geolocater.ip_lookup("127.0.0.1")}.to raise_error(RuntimeError,"Can't lookup localhost address. Please use an external IP address!")
end

it "successfully makes a HTTP request" do
Expand Down

0 comments on commit b9107cf

Please sign in to comment.