在过滤条件之前 [英] Before filter on condition

查看:164
本文介绍了在过滤条件之前的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Sinatra应用程序,默认情况下所有路线都需要用户登录。像这样:

I have a Sinatra app where all routes require a user login by default. Something like this:

before do 
  env['warden'].authenticate!
end

get :index do
  render :index
end

现在我想使用自定义的Sinatra条件来创建异常,但是如果条件是true / false / nil,我找不到一个方法来阅读。

pre $ def self.public(启用)
条件{
如果启用
放置'是'
其他
放置'否'
结束
}
结束


之前,除非公开吗?
env ['warden']。authenticate!
end

get:index do
render:index
end
$ b $ get:foo,:public => true
render:index
end

Now I would like to use a custom Sinatra condition to make exceptions, but I cannot find a way to read if the condition is true/false/nil

由于验证检查必须完成即使条件没有定义,我想我仍然必须在过滤器之前使用,但是我不确定如何访问我的自定义条件。

def self.public(enable) condition { if enable puts 'yes' else puts 'no' end } end before do # unless public? env['warden'].authenticate! end get :index do render :index end get :foo, :public => true do render :index end

推荐答案

我能解决这个问题,使用Sinatra的

解决方案

nofollow>助手和一些挖掘Sinatra的内部的。我认为这应该为你工作:

pre $ 助手做
def skip_authentication?
possible_routes = self.class.routes [request.request_method]

possible_routes.any? do | pattern,_,conditions,_ |
pattern.match(request.path_info)&&
conditions.any? {| C | c.name ==:认证}
结束
结束
结束


之前skip_authentication? || ENV [看守。验证!
end
$ b $ set(:authentication)do | enabled |
条件(:认证){true}除非已启用
结束

get:index do $ b $ render:index
end

get:foo,authentication:false do
render:index
end

helpers do def skip_authentication? possible_routes = self.class.routes[request.request_method] possible_routes.any? do |pattern, _, conditions, _| pattern.match(request.path_info) && conditions.any? {|c| c.name == :authentication } end end end before do skip_authentication? || env['warden'].authenticate! end set(:authentication) do |enabled| condition(:authentication) { true } unless enabled end get :index do render :index end get :foo, authentication: false do render :index end

这篇关于在过滤条件之前的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆