Skip to content

Instantly share code, notes, and snippets.

@clemens
Created August 20, 2014 08:30
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 clemens/3a34d74e8544926705e1 to your computer and use it in GitHub Desktop.
Save clemens/3a34d74e8544926705e1 to your computer and use it in GitHub Desktop.
url = 'http://example.com/ ?api_token=a-token&username=USERNAME' # => "http://example.com/ ?api_token=a-token&username=USERNAME"
url =~ URI.regexp(%w[http https]) # => 0
URI.parse(url) # => URI::InvalidURIError: bad URI(is not URI?): http://example.com/ ?api_token=a-token&username=USERNAME
@Yardboy
Copy link

Yardboy commented Aug 20, 2014

url = 'http://example.com/ ?api_token=a-token&username=USERNAME' # => "http://example.com/ ?api_token=a-token&username=USERNAME"
url.match(URI.regexp(%w[http https])).to_a.first == url # => false

url = 'http://example.com/?api_token=a-token&username=USERNAME' # => "http://example.com/?api_token=a-token&username=USERNAME"
url.match(URI.regexp(%w[http https])).to_a.first == url # => true

url = 'zztop://example.com/?api_token=a-token&username=USERNAME' # => "zztop://example.com/?api_token=a-token&username=USERNAME"
url.match(URI.regexp(%w[http https])).to_a.first == url # => false
```ruby

@clemens
Copy link
Author

clemens commented Aug 20, 2014

Ah, so basically URI.regexp seems to match all URIs in a given string and not just one. That explains something. Thanks for helping me see that!

I guess the proper solution would be to normalize the URI like xxx posted over at the HTTParty repo (jnunemaker/httparty#154) and then use the normalized URI which has spaces substituted with + or %20.

However, in my app I've just done it like this for now:

def validate_webhook_url
  return if webhook_url.blank?

  url = URI.parse(webhook_url) rescue nil

  errors.add(:webhook_url, :invalid) if url.blank? || url.scheme !~ /\Ahttps?\z/
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment