Creating routes at run-time

Hey guys. In Rails 2, is there a way to create a route at run-time? I
want to do this because a gem that I'm writing requires a single
resource route, and I'd prefer that the gem create it at run-time
instead of forcing the user to define the route in routes.rb .

While trying to figure this out, I discovered that calling
    ActionController::Routing::Routes.draw do |map|
        # my gem's route here
causes all of the routes in routes.rb to be removed.

I tried copying the routes from ActionController::Routing::Routes into
a new array or hash, then rebuilding them and adding my gem's route,
but couldn't get that to work. Also, it's messy and less than ideal.

So, any suggestions? I'm all ears!

If you have a plugin with a structure that looks like



Then rails will add the routes from that routes.rb file. (Don't know
if you have to have app/controllers, i've just always wanted to add a
route to a controller that was also in the plugin).

Since plugins can be packaged as gems, some variation on the above
should work


Interesting! I didn't that you could do that. Unfortunatey, I couldn't
get it to work.

$cat config/routes.rb
ActionController::Routing::Routes.draw do |map|
  map.resource :dashboard, :only => :show
  map.connect "dashboard/widgets/*path", :controller
=> :dashboards, :action => 'widget_data'
$ cat vendor/gems/acts_as_dashboard-0.0.0/config/routes.rb
puts "***** #{__FILE__}"
ActionController::Routing::Routes.draw do |map|
  map.connect 'foo/*path', :controller => :dashboards
$ rake routes
(in /home/nick/src/acts_as_dashboard_container)
dashboard GET /dashboard(.:format)
{:action=>"show", :controller=>"dashboards"}
{:action=>"widget_data", :controller=>"dashboards"}

Any idea why the gem's routes.rb isn't being processed?


I just found Section 5.4 in

"Another big change is that Rails now supports multiple routing files,
not just routes.rb. You can use RouteSet#add_configuration_file to
bring in more routes at any time – without clearing the currently-
loaded routes."

I'll check this out tonight!

In addition to
ActionController::Routing::RouteSet#add_configuration_file , there's
also #add_named_route , and simply #add_route . How convenient!