Allow custom options for conditions

Example:

module Sinatra
  module CustomConditionFu
    def authorized_for(*roles)
      condition { roles.include?(user.role) }
    end
  end
  register CustomConditionFu
end

delete '/everything', :authorized_for => [:admin] do
  everything.delete
end
This commit is contained in:
Blake Mizerany 2009-04-06 16:58:39 -07:00 committed by Ryan Tomayko
parent da37a88395
commit b8b9072a1a
2 changed files with 29 additions and 3 deletions

View File

@ -763,9 +763,10 @@ module Sinatra
private
def route(verb, path, opts={}, &block)
host_name opts[:host] if opts.key?(:host)
user_agent opts[:agent] if opts.key?(:agent)
accept_mime_types opts[:provides] if opts.key?(:provides)
host_name opts.delete(:host) if opts.key?(:host)
user_agent opts.delete(:agent) if opts.key?(:agent)
accept_mime_types opts.delete(:provides) if opts.key?(:provides)
opts.each {|o, args| send(o, *args)}
pattern, keys = compile(path)
conditions, @conditions = @conditions, []

View File

@ -693,6 +693,31 @@ class RoutingTest < Test::Unit::TestCase
assert_equal 'ab', body
end
it 'allows for condition helper sugar' do
condition_helpers = Module.new {
def custom_condition_fu(one, two)
condition { one == 1 && two == 2 }
end
}
Sinatra::Base.register(condition_helpers)
mock_app {
get '/notit', :custom_condition_fu => [0, 0] do
'notit'
end
get '/it', :custom_condition_fu => [1, 2] do
'it'
end
}
get '/notit'
assert not_found?
get '/it'
assert ok?
end
# NOTE Block params behaves differently under 1.8 and 1.9. Under 1.8, block
# param arity is lax: declaring a mismatched number of block params results
# in a warning. Under 1.9, block param arity is strict: mismatched block