Skip to content

Instantly share code, notes, and snippets.

@bhauman
Created December 2, 2009 02:08
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 bhauman/246866 to your computer and use it in GitHub Desktop.
Save bhauman/246866 to your computer and use it in GitHub Desktop.
sometimes you you ask for a hostname and you want to offer your user the option of entering the 'http://' or not
def scheme_host(url)
begin
p_uri = URI.parse(url)
p_uri.scheme = 'http'
return nil if p_uri.host == 'http'
p_uri.host = url if !p_uri.host
p_uri.select(:scheme, :host).join('://')
rescue URI::InvalidURIError
nil
rescue URI::InvalidComponentError
nil
end
end
#shoulda tests
scheme_host('google.com').should == 'http://google.com'
scheme_host('http://google.com').should == 'http://google.com'
scheme_host('http://goog__le.com').should == nil
scheme_host('http://http://goog__le.com').should == nil
scheme_host('http://').should be_nil
scheme_host('/google.com').should be_nil
scheme_host('http:/google.com').should be_nil
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment