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?
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?
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
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