Skip to content

Instantly share code, notes, and snippets.

@mynewsdesk
Created January 26, 2010 13:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mynewsdesk/286842 to your computer and use it in GitHub Desktop.
Save mynewsdesk/286842 to your computer and use it in GitHub Desktop.
module URI
# Safe alternative to URI.parse(uri_string).host to avoid exception being thrown
# on URLs with trailing spaces or invalid URLs. See also:
# http://www.practicalguile.com/2007/09/15/raising-uriinvalidurierror-from-a-perfectly-valid-uri/
def self.host(uri_string)
begin
URI.parse(uri_string.try(:strip)).host
rescue URI::InvalidURIError
nil
end
end
end
describe URI do
describe "host method" do
it "can parse valid URLs" do
URI.host("http://www.dn.se/ekonomi/").should == "www.dn.se"
URI.host("http://dn.se/ekonomi/").should == "dn.se"
URI.host("http://192.0.0.1/ekonomi/").should == "192.0.0.1"
URI.host("http://www.newsdesk.se").should == "www.newsdesk.se"
end
it "returns nil for trailing space and invalid URLs" do
URI.host(" http://www.dn.se/ekonomi/ ").should == "www.dn.se"
URI.host("f o o b a r").should be_nil
URI.host("").should be_nil
URI.host(" ").should be_nil
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment