From 7c0c14fc6fbaa3481060880de60b393da69c150a Mon Sep 17 00:00:00 2001 From: Blake Mizerany Date: Wed, 21 Nov 2007 15:27:24 -0800 Subject: [PATCH] use DSL for default error events --- lib/sinatra.rb | 25 ++++++++++++++++++------- test/dispatching_test.rb | 2 ++ 2 files changed, 20 insertions(+), 7 deletions(-) diff --git a/lib/sinatra.rb b/lib/sinatra.rb index 3237367..13d0b49 100644 --- a/lib/sinatra.rb +++ b/lib/sinatra.rb @@ -66,12 +66,14 @@ module Sinatra end end - Error = Proc.new do - "#{$!.message}\n\t#{$!.backtrace.join("\n\t")}" - end + def setup_default_events! + error 500 do + "#{$!.message}\n\t#{$!.backtrace.join("\n\t")}" + end - NotFound = Proc.new do - "

Not Found

" + error 404 do + "

Not Found

" + end end def request_types @@ -94,7 +96,7 @@ module Sinatra def determine_route(verb, path) found = routes[verb].eject { |r| r.match(path) } - found || routes[404] || NotFound + found || routes[404] end def call(env) @@ -111,7 +113,7 @@ module Sinatra context.finish rescue => e raise e if config[:raise_errors] - route = Sinatra.routes[500] || Error + route = Sinatra.routes[500] context.status 500 context.body Array(context.instance_eval(&route.block)) context.finish @@ -123,6 +125,10 @@ module Sinatra route end + def define_error_route(num, &b) + routes[num] = b + end + class Route URI_CHAR = '[^/?:,&#]'.freeze unless defined?(URI_CHAR) @@ -154,3 +160,8 @@ end def get(path, &b) Sinatra.define_route(:get, path, &b) end + +def error(num, &b) + raise 'You must specify a block to assciate with an error' if b.nil? + Sinatra.define_error_route(num, &b) +end diff --git a/test/dispatching_test.rb b/test/dispatching_test.rb index 4956667..aad1591 100644 --- a/test/dispatching_test.rb +++ b/test/dispatching_test.rb @@ -12,6 +12,7 @@ context "Dispatching" do setup do Sinatra.routes.clear + Sinatra.setup_default_events! end specify "should return the correct block" do @@ -104,6 +105,7 @@ context "An Event in test mode" do setup do Sinatra.routes.clear + Sinatra.setup_default_events! end specify "should raise errors to top" do -- 2.11.4.GIT