Topic: Executing multiple controllers with one request

I'm designing an Ajax RPC Router for Rails using Ext JS library.

I need to dispatch actions to multiple controllers during a single request.

I made a piece of Rack Middleware and plugged it in to Rails initializer in environment.rb

Rails::Initializer.run do |config|
    config.middleware.use MyRouter "rpc"
end

The following Rack Middleware is *far* from being complete.  I show dispatching to hard-coded controller/actions here as an example.

class MyRouter
  def initialize(app, rpc_path)
    @app = app
    @rpc_path = rpc_path
  end

  def call(env)
    if env["PATH_INFO"].match("^"+@rpc_path)  # <-- detect rpc path
      output = [] # <-- capture each controller's response into an array
      ["company", "user"].each do |controller_name|
        env["PATH_INFO"] = "/#{controller_name}/load"  # <-- re-write env
        env["REQUEST_URI"] = "/#{controller_name}/load"
        output << @app.call(env)  # <-- Is it kosher to call multiple controllers like this??
      end           
      [200, {"Content-Type" => "text/html"}, process_response(output)]
    else
      @app.call(env)
    end
  end

  def process_response(list)
      # iterate array of controller responses and return the body from each.     
  end
end


Is it OK to dispatch to multiple controllers like this?
In Merb, I implemented this RPC functionality using merb-parts.
Is there a better way in Rails?

Last edited by christocracy (2009-04-30 20:01:53)