在过滤条件之前

时间:2014-03-13 13:37:04

标签: 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 '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

由于即使未定义条件也必须进行身份验证检查,我想我仍然必须使用before过滤器,但我不知道如何访问我的自定义条件。

1 个答案:

答案 0 :(得分:1)

我能够使用Sinatra的helpers来解决这个问题,并且有些人正在挖掘Sinatra的internals。我认为这对你有用:

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
相关问题