Filter 前过滤器开启条件

Filter 前过滤器开启条件,filter,sinatra,Filter,Sinatra,我有一个Sinatra应用程序,默认情况下,所有路线都需要用户登录。大概是这样的: before do env['warden'].authenticate! end get :index do render :index end 现在我想使用一个定制的Sinatra条件来创建异常,但是我找不到一种方法来读取该条件是否为true/false/nil def self.public(enable) condition { if enable puts 'ye

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

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

get :index do
  render :index
end
现在我想使用一个定制的Sinatra条件来创建异常,但是我找不到一种方法来读取该条件是否为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和一些深入研究Sinatra的方法来解决这个问题。我认为这应该适合你:

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

公共方法在before上下文中不可用,因为它被定义为类方法。您是否检查过该方法何时被定义为实例方法(无self)?如果我将该方法定义为实例(无self),那么我将无法将其用作规则条件,并且我希望保留在DSL中编写公共URL的方式。在阅读请求对象的条件之前,或者将public=>false定义为任何规则的默认条件之前,我一直在考虑。在任何情况下,我只是想用一种简单的方法来指定默认规则的一些例外情况。我注意到的是,条件似乎是在筛选之后解析的,而这正是我用尽心思的时候。到目前为止,我解决了这个问题,只在检测到登录url时才有条件跳过身份验证,但这并不是未来的证明。