[Nitro] "magic" mapping of controllers possible?

Michael Fellinger manveru at weez-int.com
Wed Jun 21 22:51:11 EDT 2006

Hey Lars,

I am all for doing something like that, but the problem is that just about 
everybody has a different structure of the projects they work on.
However, here is how i would do that stuff for my own project - possible 
problems that might need an additional variable or a convention in the 
community (imho not the worst thing, since one can override it): 

* the controller mapped to / is even in my own projects inconsistent, either
  BaseController, RootController, DefaultController, MainController,
  HomepageController and whatnot else...
* the place where the controllers are is usually /src or /controllers - but
  there are endless possibilities and i have no idea where other people put
  their stuff into

def try &block
  rescue Object

def fetch_mount point
  if point == '/'
    file, controller = 'controller.rb', 'RootController'
    base = point.gsub('/', '')
    file, controller = "controllers/#{base}", "#{base.capitalize}Controller"
  # check if file is in $:
  Logger.debug 'missing #{file} for #{controller}' unless try{require file}

  if Module.const_defined? controller
    raise NameError, "missing Controller #{controller} for #{point}"

module Nitro
  class Server
    def self.automap *arr
      Nitro::Server.map = Hash[*arr.map{|m| [m, fetch_mount(m)] }.flatten]

# i just worked out the one above, you can of course do it in a short and
# dirty oneliner without meaningful errors :)
# the directory-structure is the one i use by default

%w{Root Foo Bar Baz}.each{|c| eval("class #{c}Controller; end")}
# ["Root", "Foo", "Bar", "Baz"]

Nitro::Server.auto_map = "/", "/foo", "/bar", "/baz"

On Thursday 22 June 2006 03:21, Lars Olsson wrote:
> Hi list!
> When mapping multiple controllers (via Nitro::Server.map) all Controller
> classes has to be loaded/required before I put them in the map. To my
> understanding this means that even if I only visit a particular url
> (/foo) Nitro still have to load both the DefaultController and the
> BarController. Is this correct?
> # sample run.rb
> require 'nitro'
> class DefaultController
>      def index
>          "DefaultController"
>      end
> end
> class FooController
>      def index
>          "FooController"
>      end
> end
> class BarController
>      def index
>          "BarController"
>      end
> end
> Nitro::Server.map =
>      {
>          '/' => DefaultController,
>          '/foo' => FooController,
>          '/bar' => BarController
>      }
> Nitro.run
> # end sample
> Is it in any way possible to create a "magic" map that maps the request
> name to a partical controller, i.e:
> "/" maps to controllers/DefaultController (special case)
> "/foo" maps to controllers/FooController
> "/bar" maps to controllers/BarController
> "/baz" maps to controllers/BazController
> # you get the idea...
> Kindly
> /Lasso

More information about the Nitro-general mailing list