ruby 在 Sinatra 中,您如何制作一个“之前”过滤器来匹配除某些路线之外的所有路线

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7703962/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 04:22:22  来源:igfitidea点击:

in Sinatra how do you make a "before" filter that matches all routes except some

rubysinatra

提问by lms

I have a Ruby Sinatra app and I have some code which I need to execute on all routes except for a few exceptions. How do I do this?

我有一个 Ruby Sinatra 应用程序,我有一些代码需要在所有路由上执行,除了少数例外。我该怎么做呢?

If I wanted to execute the code on selected routes (whitelist style) I'd do this:

如果我想在选定的路线上执行代码(白名单样式),我会这样做:

['/join', "/join/*", "/payment/*"].each do |path|
    before path do
        #some code
    end
end

How do I do it the other way round though (blacklist style)? I want to match all routes except '/join', '/join/*'and '/payment/*'

我如何反过来做(黑名单样式)?我想匹配除'/join','/join/*''/payment/*'

回答by Konstantin Haase

With negative look-ahead:

负前瞻:

before /^(?!\/(join|payment))/ do
  # ...
end

With pass:

pass

 before do
   pass if %w[join payment].include? request.path_info.split('/')[1]
   # ...
 end

Or you could create a custom matcher.

或者您可以创建一个自定义匹配器

回答by OneChillDude

What I did to make a "before all, except..." filter is use a splat, and then run code on splat conditions.

我所做的制作“之前,除了...”过滤器是使用 splat,然后在 splat 条件下运行代码。

before '/*' do
  unless params[:splat] == 'nofilter' || params[:splat] == 'beta'
    redirect '/beta'
  end
end

This allowed me to make a before filter with a redirect that didn't create a redirect loop

这使我可以使用未创建重定向循环的重定向创建一个 before 过滤器

回答by ben

You can use Regular Expressions for routing in sinatra

您可以使用正则表达式在 sinatra 中进行路由

for example:

例如:

get %r{/hello/([\w]+)} do |c|
   "Hello, #{c}!"
end

taken from here. there you can find further informations.

取自这里。在那里您可以找到更多信息。

to build and test your regex you can use http://rubular.com/

要构建和测试您的正则表达式,您可以使用http://rubular.com/