有没有办法将字符串附加到红宝石Regexp的前面

时间:2013-12-30 19:04:55

标签: 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 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_url(/\/pirates.*/)

匹配

"https://test.example.com/pirates"
"https://test.example.com/pirates?some%20parameters"

不匹配:

"/pirates"
"https://test.example.compirates"
"https://test.example.com/pirate"

有没有办法将Regexp附加到字符串上?

2 个答案:

答案 0 :(得分:1)

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_request以显示您应该期待的内容,但我感觉您做错了什么

答案 1 :(得分:0)

我发现这样做的最好方法是:

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

此方法通过获取字符串的正则表达式来工作。将正则表达式的源代码添加到传入的正则表达式的正则表达式源代码中。最后获得正则表达式。

如果您找到更好的方法,请告诉我