Remapping routes dynamically?

I’m trying to figure out how to merge the utility of namespaces with
user roles. For example, I have a very simple system of buyers and
sellers and a user is either part of a buyer account or a seller
account (not both!). I am trying to figure out if I can define routes
that are top-level identical but based upon the user’s account type,
maps to a namespace.

For example, imagine I have a ProductsController class for Buyers and
a ProductsController class for Sellers. I’m doing this because there
is enough difference in what a Buyer would do and a Seller would do,
as opposed to a single class that does some user-role-type logic.

So, I have “app/controllers/buyers/products_controller.rb” and “app/
controllers/sellers/products_controller.rb”. In a normal namespaced-
defined route, I’d typically have:

map.namespace :buyers do |buyers|
buyers.resources :products
end

and

map.namespace :sellers do |sellers|
sellers.resources :products
end

So I get routes like: ‘/buyers/products/’ => :index action on
products_controller in the buyers namespace.

But, what I’d REALLY love is something like:

‘/products’ => calls ‘index’ action but on the products_controller as
defined by the logged in user’s account type (buyer or seller). And,
of course, then I’d need some way to handle the case where the user
tries the URL but hasn’t logged in, perhaps even just a redirect to a
login controller.

Anyway, does this make sense? Is this even possible? Can someone help
me with this or with a different way to think about it.

I know I can just do the normal namespacing, but the URLs would be so
much neater, in my case, if I could ditch the prefix in the URLs.

TIA!

-Danimal

The more I thought about this, the more trouble it’ll cause. Not to
mention that the routes mapping is loaded at server start, not per
request, so I can’t do any dynamic hooks there. The other option I
thought of was to have a generic “catch-all” route and work it like a
dispatcher, but then I’d be circumventing all of routing and building
my own route parser. Ug!

What I think will really work is to put a before_filter on controllers
that need to be handled by different roles and keep the distinctions
in the controller. So, for example, have a single ProductsController
but based on the before_filter set some things or call different
methods or whatever.

-Danimal

I think you were on the right track initially. Use namespaces for
your buyers and sellers as you were planning. However, leave your
login controller (session from restful_authentication or whatever) out
in the un-namespaced area. Once the user has been authenticated you
can send them to their appropriate buyer or seller ‘home page’ and all
the rest should remain within than namspace easily enough (either
because you use xxx_path named routes or because you explicitly use
the namespaced xxx_url).