1

In the Sinatra README, there is a section called Custom Route Matchers with the following example:

class AllButPattern
  Match = Struct.new(:captures)

  def initialize(except)
    @except   = except
    @captures = Match.new([])
  end

  def match(str)
    @captures unless @except === str
  end
end

def all_but(pattern)
  AllButPattern.new(pattern)
end

get all_but("/index") do
  # ...
end

Would anyone be helpful enough to talk me through how this works? The bit I'm not sure about is why the example has the Match struct and what captures are. The user can't set the @captures instance variable, just the @except one; so how is captures used?

4

1 回答 1

3

当一个路由被处理时,它将参数传递给get(或其他),并将路径作为参数post发送到该对象的match方法。它期望返回nil意味着它不匹配,或者捕获数组。该对象通常是一个字符串或一个正则表达式,它们都有一个match方法。

capturesSinatra在处理路由时也会调用对象的方法。该示例使用结构作为一种简单的方法来设置和响应对象,该对象本身将响应captures,并放入数组中,因为这captures通常会返回。它是空的,因为该字符串尚未检查捕获,它实际上是一个否定过滤器。因此,我更喜欢使用before过滤器来做这样的事情,但是找到清晰有用的例子总是很困难。

于 2013-08-13T15:57:02.173 回答