Ruby Sinatra示例中的自定义路由匹配器是如何工作的?
在中,有一个名为的部分,其示例如下:Ruby Sinatra示例中的自定义路由匹配器是如何工作的?,ruby,routes,sinatra,Ruby,Routes,Sinatra,在中,有一个名为的部分,其示例如下: 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) AllBu
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
有人能帮我解释一下这是怎么回事吗?我不确定的是,为什么示例中有Match
struct以及捕获的内容是什么。用户不能设置@captures
实例变量,只能设置@除了一个;那么如何使用捕获
。它期望返回nil
,这意味着它不匹配,或者返回一个捕获数组。对象通常是字符串或正则表达式,它们都有match
方法
。该示例使用结构作为设置和响应对象的简单方法,对象本身将响应捕获
,并放入数组中,因为捕获
通常会返回数组。它是空的,因为没有检查字符串的捕获,它实际上是一个负过滤器。因此,我更愿意这样做,但要找到清晰有用的例子总是很困难的。@captures
持有“match everything”类,该类的行为类似于使用captures
方法的东西。除非字符串与构造函数中传递的内容完全匹配,否则将返回它。我的意思是,这里没有太多的事情发生。它几乎是一个通配符,你可以使用它。你想知道它是如何运作的吗?那太好了@Doon。你能在@DaveNewton上进一步阐述吗?我不清楚困惑在哪里;你到底不明白什么?