Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic URL -> Controller mapping for routes in Rails

I would like to be able to map URLs to Controllers dynamically based on information in my database.

I'm looking to do something functionally equivalent to this (assuming a View model):

map.route '/:view_name',
    :controller => lambda { View.find_by_name(params[:view_name]).controller }

Others have suggested dynamically rebuilding the routes, but this won't work for me as there may be thousands of Views that map to the same Controller

like image 821
Daniel Beardsley Avatar asked Apr 07 '10 22:04

Daniel Beardsley


1 Answers

This question is old, but I found it interesting. A fully working solution can be created in Rails 3 using router's capability to route to a Rack endpoint.

Create the following Rack class:

    class MyRouter
      def call(env)
        # Matched from routes, you can access all matched parameters
        view_name= env['action_dispatch.request.path_parameters'][:view_name]

        # Compute these the way you like, possibly using view_name
        controller= 'post' 
        my_action= 'show'

        controller_class= (controller + '_controller').camelize.constantize
        controller_class.action(my_action.to_sym).call(env)
      end
    end

In Routes

    match '/:view_name', :to => MyRouter.new, :via => :get

Hint picked up from http://guides.rubyonrails.org/routing.html#routing-to-rack-applications which says "For the curious, 'posts#index' actually expands out to PostsController.action(:index), which returns a valid Rack application."

A variant tested in Rails 3.2.13.

like image 72
Deepak Kumar Avatar answered Oct 17 '22 01:10

Deepak Kumar