Permalink
Browse files

Define routes as methods on Sinatra::Base...

This makes deciphering a stacktrace much easier

RecordNotFound - No Post for id 3
./x.rb:9:in `route { GET /posts/:id }'
./lib/sinatra/base.rb:366:in `send'
./lib/sinatra/base.rb:366:in `invoke'
./lib/sinatra/base.rb:362:in `catch'
...
  • Loading branch information...
1 parent 59abc94 commit 524f78b3f2e6ef39c20f81a6d9b15c7a84f6157d @bmizerany bmizerany committed Jan 8, 2009
Showing with 17 additions and 7 deletions.
  1. +17 −7 lib/sinatra/base.rb
View
@@ -326,7 +326,7 @@ def dispatch!
original_params = Hash.new{ |hash,k| hash[k.to_s] if Symbol === k }
original_params.merge! @request.params
- routes.each do |pattern, keys, conditions, block|
+ routes.each do |pattern, keys, conditions, method_name|
if pattern =~ path
values = $~.captures.map{|val| val && unescape(val) }
params =
@@ -350,16 +350,22 @@ def dispatch!
catch(:pass) {
conditions.each { |cond|
throw :pass if instance_eval(&cond) == false }
- return invoke(block)
+ return invoke(method_name)
}
end
end
end
raise NotFound
end
- def invoke(block)
- res = catch(:halt) { instance_eval(&block) }
+ def invoke(handler)
+ res = catch(:halt) {
+ if handler.respond_to?(:call)
+ instance_eval(&handler)
+ else
+ send(handler)
+ end
+ }
case
when res.respond_to?(:to_str)
@response.body = [res]
@@ -528,10 +534,10 @@ def accept_mime_types(types)
def get(path, opts={}, &block)
conditions = @conditions.dup
- route 'GET', path, opts, &block
+ _, _, _, method_name = route('GET', path, opts, &block)
@conditions = conditions
- head(path, opts) { invoke(block) ; [] }
+ head(path, opts) { invoke(method_name) ; [] }
end
def put(path, opts={}, &bk); route 'PUT', path, opts, &bk; end
@@ -547,8 +553,12 @@ def route(method, path, opts={}, &block)
pattern, keys = compile(path)
conditions, @conditions = @conditions, []
+ method_name = "route { #{method} #{path} }"
+
+ define_method(method_name, &block)
+
(routes[method] ||= []).
- push [pattern, keys, conditions, block]
+ push([pattern, keys, conditions, method_name]).last
end
def compile(path)

0 comments on commit 524f78b

Please sign in to comment.