16 map { |k,v| "#{k}=#{URI.escape(v)}" }.join('&')
20 self.inject({}) { |h,(k,v)| h[k.to_sym] = v; h }
24 reject { |k,v| !keys.include?(k) }
30 Proc.new { |*args| args.shift.__send__(self, *args) }
36 self.inject({}) { |h, (k, v)| h[k] = v; h }
40 Proc.new { |*args| args.shift.send(self[0], args + self[1..-1]) }
52 find { |e| result = block[e] and break result }
59 EventContext = Struct.new(:request, :response) do
60 def method_missing(name, *args)
61 if args.size == 1 && response.respond_to?("#{name}=")
62 response.send("#{name}=", args.first)
64 response.send(name, *args)
69 def setup_default_events!
71 "#{$!.message}\n\t#{$!.backtrace.join("\n\t")}"
81 @request_types ||= [:get, :put, :post, :delete]
85 @routes ||= Hash.new do |hash, key|
86 hash[key] = [] if request_types.include?(key)
98 def determine_route(verb, path)
99 found = routes[verb].eject { |r| r.match(path) }
104 request = Rack::Request.new(env)
105 response = Rack::Response.new
106 route = determine_route(
107 request.request_method.downcase.to_sym,
110 context = EventContext.new(request, response)
112 result = context.instance_eval(&route.block)
113 context.body = Array(result.to_s)
116 raise e if config[:raise_errors]
117 route = Sinatra.routes[500]
119 context.body Array(context.instance_eval(&route.block))
124 def define_route(verb, path, &b)
125 routes[verb] << route = Route.new(path, &b)
129 def define_error_route(num, &b)
135 URI_CHAR = '[^/?:,&#]'.freeze unless defined?(URI_CHAR)
136 PARAM = /:(#{URI_CHAR}+)/.freeze unless defined?(PARAM)
138 attr_reader :block, :path
140 def initialize(path, &b)
141 @path, @block = path, b
143 regex = path.to_s.gsub(PARAM) do
144 @param_keys << $1.intern
147 @pattern = /^#{regex}$/
148 @struct = Struct.new(:block, :params)
152 return nil unless path =~ @pattern
153 params = @param_keys.zip($~.captures.map(&:from_param)).to_hash
154 @struct.new(@block, params)
162 Sinatra.define_route(:get, path, &b)
166 raise 'You must specify a block to assciate with an error' if b.nil?
167 Sinatra.define_error_route(num, &b)
170 Sinatra.setup_default_events!