ruby - Sinatra 示例中的自定义路由匹配器如何工作?

标签 ruby routes sinatra

Sinatra README , 有一个名为 Custom Route Matchers 的部分使用以下示例:

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 结构以及什么是 captures。用户不能设置@captures实例变量,只能设置@except;那么captures是如何使用的呢?

最佳答案

When a route is processed, it takes the argument to get (or post or whatever), and sends to that object's match method with the path as an argument .它期望返回 nil ,这意味着它不匹配,或者返回一个捕获数组。该对象通常是一个字符串或一个正则表达式,它们都有一个 match 方法。

Sinatra also calls on the captures method of the object when it is processing a route .该示例使用一个结构作为一种简单的方法来设置和响应一个对象,该对象本身将响应 captures,并放入一个数组,因为这就是 captures 通常会做的返回。它是空的,因为还没有检查字符串是否被捕获,它实际上是一个负过滤器。因此,我更喜欢 the use of a before filter做这样的事情,但总是很难找到清晰有用的例子。

关于ruby - Sinatra 示例中的自定义路由匹配器如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18208094/

相关文章:

javascript - 如何在 VueJS 2.0 中进行路由

java - 如何在谷歌地图上创建从用户位置到用户选择的项目覆盖的路线/导航?

ruby - 在 ruby​​ 和 sinatra 中索引和搜索文本文件

ruby-on-rails - 如何使用 rspec 测试条件 ActiveRecord after_update 回调?

Ruby 默认赋值 ( ||= ) 与拯救错误

html - 在 CakePHP 中将命名路由转换为散列 (#)

ruby - sinatra 和 tweetstream 不能一起工作

ruby-on-rails - vim 和 Ruby on Rails

ruby-on-rails - ActiveModelSerializers gem : how to pass parameter to serializer

ruby - 从 sinatra 的帖子调用系统