From f6ca4bdef9a1d53c0ac744adde9cffac287c355d Mon Sep 17 00:00:00 2001 From: Blake Mizerany Date: Wed, 21 Nov 2007 02:18:27 -0800 Subject: [PATCH] routes determined --- lib/sinatra.rb | 24 +++++++++++++++++++++--- test/dispatching_test.rb | 14 ++++++++++++++ test/helper.rb | 3 +++ test/route_test.rb | 4 +--- 4 files changed, 39 insertions(+), 6 deletions(-) create mode 100644 test/dispatching_test.rb create mode 100644 test/helper.rb diff --git a/lib/sinatra.rb b/lib/sinatra.rb index af6e3c90..d14fa7b6 100644 --- a/lib/sinatra.rb +++ b/lib/sinatra.rb @@ -21,26 +21,44 @@ class Array def to_hash self.inject({}) { |h, (k, v)| h[k] = v; h } end + + def to_proc + Proc.new { |*args| args.shift.send(self[0], args + self[1..-1]) } + end end + +module Enumerable + def eject(&block) + find { |e| result = block[e] and break result } + end +end + + module Sinatra extend self def request_types - @request_types ||= %w(GET PUT POST DELETE) + @request_types ||= [:get, :put, :post, :delete] end - def events - @events ||= Hash.new do |hash, key| + def routes + @routes ||= Hash.new do |hash, key| hash[key] = [] if request_types.include?(key) end end + def determine_event(verb, path) + routes[verb].eject { |r| r.match(path) } + end + class Route URI_CHAR = '[^/?:,&#]'.freeze unless defined?(URI_CHAR) PARAM = /:(#{URI_CHAR}+)/.freeze unless defined?(PARAM) + attr_reader :block, :path + def initialize(path, &b) @path, @block = path, b @param_keys = [] diff --git a/test/dispatching_test.rb b/test/dispatching_test.rb new file mode 100644 index 00000000..ce396e37 --- /dev/null +++ b/test/dispatching_test.rb @@ -0,0 +1,14 @@ +require File.dirname(__FILE__) + '/helper' + +context "Dispatching" do + + specify "should return the correct block" do + Sinatra.routes[:get] << r = Sinatra::Route.new('/') do + 'main' + end + + result = Sinatra.determine_event(:get, '/') + result.block.should.be r.block + end + +end diff --git a/test/helper.rb b/test/helper.rb new file mode 100644 index 00000000..26d69418 --- /dev/null +++ b/test/helper.rb @@ -0,0 +1,3 @@ +require File.dirname(__FILE__) + "/../lib/sinatra" +require 'test/spec' +require 'mocha' diff --git a/test/route_test.rb b/test/route_test.rb index d26c81a1..ab02e761 100644 --- a/test/route_test.rb +++ b/test/route_test.rb @@ -1,6 +1,4 @@ -require File.dirname(__FILE__) + "/../lib/sinatra" -require 'test/spec' -require 'mocha' +require File.dirname(__FILE__) + '/helper' context "A Route in general" do