starting to use Rack
[chew.git] / lib / chew / router.rb
blob5a24b420f1375fe2e11227efc6ea60df465b9429
1 require 'http11' # for Mongrel::URIClassifier
3 module Chew
4   # Users put Actions inside this module to be given automatic routing paths
5   module Root
6   end
7   
8   class Router
9     def initialize
10       # the keys of @classifiers are the HTTP methods
11       @classifiers = Hash.new
12       Chew::Request::METHODS.each do |m|
13         @classifiers[m.to_sym] = Mongrel::URIClassifier.new
14       end
15       load_all_module_routes
16     end
17     
18     def load_all_module_routes
19       load_module_routes(Chew::Root, '/')
20     end
21     
22     def resolve(request)
23       _, rel_path, action = @classifiers[request.method].resolve(request.path_info)
24       [action, rel_path]
25     end
26     
27     private
28     
29     def load_module_routes(m, path)
30       m.submodules.each do |n|
31         n_path = File.join(path, n.last_name)
32         if n < Chew::Action
33           @classifiers[n.method].register(n_path, n)
34         else
35           load_module_routes(n, n_path)
36         end
37       end
38     end
39   end  
40 end