lib/nitro/dispatcher.rb in nitro-0.9.5 vs lib/nitro/dispatcher.rb in nitro-0.10.0

- old
+ new

@@ -26,22 +26,22 @@ # # Input: # # [+controllers+] # Either a hash of controller mappings or a single - # controller that gets mapped to :index. + # controller that gets mapped to :root. # # [+apis+] # A hash of apis supported by the Dispatcher. def initialize(controllers = nil, apis = nil) @root = 'root' if controllers and controllers.is_a?(Class) and controllers.ancestors.include?(Controller) - @controllers = { :index => controllers } + @controllers = { :root => controllers } else - @controllers = controllers || { :index => Controller } + @controllers = controllers || { :root => SimpleController } end @apis = apis end @@ -55,11 +55,11 @@ # mount points to controllers. # # === Examples # # dispatcher.mount { - # :index => MainController # mounts / + # :root => MainController # mounts / # 'users' => UsersController # mounts /users # } def mount(controllers) (@controllers ||= {}).update(controllers) @@ -77,46 +77,73 @@ end # Processes the path and dispatches to the corresponding # controller/action pair. # The base returned contains a trailing '/'. + # + # [+path+] + # The path to dispatch. + # + # [:context] + # The dispatching context. - def dispatch(path) + def dispatch(path, context) api = :xhtml if @apis @apis.each { |k, v| api = k if path.slice!(/#{k}\//) } end parts = path.split('/') case parts.size when 0 + # / -> root.index base = @root - controller_class = @controllers[:index] + klass = controller_class_for(:root, context) action = 'index' when 2 - if controller_class = @controllers[parts[1]] + if klass = controller_class_for(parts[1], context) + # controller/ -> controller.index base = "#{@root}/#{parts[1]}" action = 'index' else + # action/ -> root.action base = @root - controller_class = @controllers[:index] + klass = controller_class_for(:root, context) action = parts[1] end when 3 + # controller/action/ -> controller.action base = "#{@root}/#{parts[1]}" - controller_class = @controllers[parts[1]] + klass = controller_class_for(parts[1], context) action = parts[2] end content_type = @apis ? @apis[:api] : 'text/html' - return controller_class, "__#{api}__#{action}", base, content_type + return klass, "__#{api}__#{action}", base, content_type end alias_method :split_path, :dispatch - + + # Get the controller for the given key. + # Also handles reloading of controllers. + + def controller_class_for(key, context) + klass = @controllers[key] + + if context[:__RELOADED__].nil? and (:full == Rendering.reload) and klass + def_file = klass::DEF_FILE + Controller.remove_subclasses + load(def_file) + klass = @controllers[key] = Object.const_get(klass.name.intern) + context[:__RELOADED__] = true + end + + return klass + end + end end