Ruby on rails 检查字符串是否为有效的URI

Ruby on rails 检查字符串是否为有效的URI,ruby-on-rails,ruby,Ruby On Rails,Ruby,场景: a='some%20string' 乌里(a)# 如何在将字符串传递给URI之前检查它是否是有效的URI?我找不到方法,但查看forURI,它执行一个简单的检查: case uri when '' # null uri when @regexp[:ABS_URI] # ... when @regexp[:REL_URI] # ... else raise InvalidURIError, "bad URI(is not URI?): #{uri}" end URI()

场景:

a='some%20string'

乌里(a)#


如何在将字符串传递给URI之前检查它是否是有效的URI?

我找不到方法,但查看for
URI
,它执行一个简单的检查:

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

if URI::DEFAULT_PARSER.regexp[:ABS_URI] =~ a || URI::DEFAULT_PARSER.regexp[:REL_URI] =~ a
  # valid
end

您仍然可以使用原始方法,只需将其包装为某种错误处理:

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

URI('some%20string')
给了我
#
也许我对这个问题的回答可以帮助你:-它与常规URI.extract。。因此,您可以从字符串中提取URI并传递它..我同意这个答案,因为
Addressable::URI
具有迄今为止我经历过的最好的URI处理:
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