-1

Scenario:

a = 'some%20string';

URI(a) # throws

URI::InvalidURIError: bad URI(is not URI?)

How do I check if a string is a valid URI before passing it to URI?

Denim Datta
  • 3,740
  • 3
  • 27
  • 53
shankardevy
  • 4,290
  • 5
  • 32
  • 49
  • `URI('some%20string')` gives me `#` – Stefan Aug 21 '13 at 10:29
  • maybe my answer on this question could help you: http://stackoverflow.com/questions/16234613/validate-presence-of-url-in-html-text/16238176#16238176 - it works with general URI.extract.. so you can extract the URI out of your string and pass it.. – Matthias Aug 21 '13 at 10:55
  • I'd go with this answer, as `Addressable::URI` has the best URI-handling I've experienced so far: http://stackoverflow.com/a/11958835/215168 – Abe Voelker Aug 21 '13 at 21:14

2 Answers2

2

You can still use the original method asked, just wrap it in some sort of error handling:

require 'uri'

u = nil
begin
  u = URI('hi`there')
rescue URI::InvalidURIError => e
  puts "error: #{e}"  #handle error
end

p u if u  #do something if successful
icy
  • 914
  • 6
  • 12
1

I couldn't find a method, but looking at the source code for URI, it performs a simple check:

case uri
when ''
  # null uri
when @regexp[:ABS_URI]
  # ...
when @regexp[:REL_URI]
  # ...
else
  raise InvalidURIError, "bad URI(is not URI?): #{uri}"
end

URI() uses the default parser, so something like this should work:

if URI::DEFAULT_PARSER.regexp[:ABS_URI] =~ a || URI::DEFAULT_PARSER.regexp[:REL_URI] =~ a
  # valid
end
Stefan
  • 109,145
  • 14
  • 143
  • 218