Created
January 26, 2010 13:41
-
-
Save mynewsdesk/286842 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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