有没有办法将字符串附加到ruby Regexp的前面
现在我有一个方法,通常只接受一个字符串有没有办法将字符串附加到ruby Regexp的前面,ruby,regex,ruby-on-rails-3,Ruby,Regex,Ruby On Rails 3,现在我有一个方法,通常只接受一个字符串 def stub_url(endpoint = "/", auth = nil) url = "https://#{auth}test.example.com#{endpoint}" stub_request(:get, url).to_return(:status => 200) end 但我也希望接受正则表达式作为端点,所以我尝试了这样的方法 def stub_url(endpoint = "/", auth = nil) if e
def stub_url(endpoint = "/", auth = nil)
url = "https://#{auth}test.example.com#{endpoint}"
stub_request(:get, url).to_return(:status => 200)
end
但我也希望接受正则表达式作为端点,所以我尝试了这样的方法
def stub_url(endpoint = "/", auth = nil)
if endpoint.is_a?(Regexp)
# this is where I'm stuck
url =
# url should be regex
else
url = "https://#{auth}test.example.com#{endpoint}"
# url should be string
end
# stub_request can take string or Regexp
stub_request(:get, url).to_return(:status => 200)
end
例如:
stub\uURL(/\/pirates.*/)
匹配项:
"https://test.example.com/pirates"
"https://test.example.com/pirates?some%20parameters"
不匹配:
"/pirates"
"https://test.example.compirates"
"https://test.example.com/pirate"
有没有办法将Regexp附加到字符串上
def stub_url(endpoint = "/", auth = nil)
url = "https://#{auth}test.example.com"
if endpoint.is_a? Regexp
url = /#{Regexp.escape(url)}#{endpoint.source}/
else
url = "https://#{auth}test.example.com/#{endpoint}"
end
return url
#stub_request(:get, url).to_return(:status => 200)
end
stub_url(/\/pirates.*/).source # => "https://test\\.example\\.com/pirates.*"
stub_url("pirates") # => "https://test.example.com/pirates"
注
我已经删除了stub_请求,以显示您应该期望的内容,尽管我感觉您在做错事我发现最好的方法是这样的:
def stub_url(endpoint = "/", auth = nil)
if endpoint.is_a?(Regexp)
url = Regexp.new(Regexp.new("https://#{auth}test.example.com").source + endpoint.source)
# But I could make it a little simpler like below
# url = Regexp.new(/https:\/\/#{auth}test.example.com/ + endpoint.source)
else
url = "https://#{auth}test.example.com#{endpoint}"
end
stub_request(:get, url).to_return(:status => 200)
end
此方法通过获取字符串的正则表达式来工作。将该正则表达式的正则表达式源前置到传入正则表达式的正则表达式源。最后得到了它的正则表达式
如果你找到更好的方法,让我知道我的意思不是字面意义上的,但在匹配字符串后跟正则表达式的意义上,我认为我想要的仍然不清楚,我更新了很多好的调用,我现在就添加它们,我仍然不明白<代码>存根url('/pancakes')只是将
'/pancakes'
附加到url,但是存根url(/pancakes?/)
会做什么?它会创建一个与我猜的相同url匹配的正则表达式。但是我尝试它的原因是为了可以接受额外的参数(使用/\/pancakes.*/
),也许您应该使用来构建URI,而不是使用字符串争用。大概我仍然不知道如果你打电话,比如说,stud\uurl(/x(yz)?/)
会是什么。