Permalink
Browse files

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
  • Loading branch information...
1 parent da37a88 commit b8b9072a1aa3f08a4d2b18eccfe7559210ce7ac4 @bmizerany bmizerany committed with rtomayko Apr 6, 2009
Showing with 29 additions and 3 deletions.
  1. +4 −3 lib/sinatra/base.rb
  2. +25 −0 test/routing_test.rb
View
@@ -763,9 +763,10 @@ def head(path, opts={}, &bk); route 'HEAD', path, opts, &bk end
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
@@ -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

0 comments on commit b8b9072

Please sign in to comment.