title: How to route and render (dispatch) from a model in Ruby on Rails 3
body: <p>I want to dispatch (route and render) from a model. (I only care about <code>GET</code> requests and I ignore <code>Accept:</code> headers, so I only look at <code>PATH_INFO</code>.)</p>
  
  <pre><code># app/models/response.rb
  class Response &lt; ActiveRecord::Base
    # col :path_info
    # col :app_version
    # col :body, :type =&gt; :text
  
    def set_body
      params = Rails.application.routes.recognize_path(path_info, :method =&gt; :get)
      controller = "#{params[:controller].camelcase}Controller".constantize.new
      controller.action_name = params[:action]
      controller.request = ActionDispatch::Request.new('rack.input' =&gt; [])
      controller.request.path_parameters = params.with_indifferent_access
      controller.request.format = params[:format] || 'html'
      controller.response = ActionDispatch::Response.new
      controller.send params[:action]
      self.body = controller.response.body
    end
  end
  </code></pre>
  
  <p>The above code <strong>works</strong>, but it feels clunky. What's the right way to do it? I'm imagining <a href="https://stackoverflow.com/users/122162/yehuda-katz">Yehuda Katz</a> would tell me something like:</p>
  
  <pre><code>def set_body
    # [...]
    app = "#{params[:controller].camelcase}Controller".constantize.action(params[:action])
    app.process params
    self.body = app.response.body
  end
  </code></pre>
  
  <p>FWIW here's my routes file:</p>
  
  <pre><code># config/routes.rb
  MyApp::Application.routes.draw do
    resources :products                                       # GET /products.json?merchant_id=foobar
    match '/:id(.:format)' =&gt; 'contents#show', :via =&gt; 'get'  # GET /examples
    root :to =&gt; 'contents#index', :via =&gt; 'get'               # GET /
  end
  </code></pre>
  
  <p>See also: <em><a href="https://stackoverflow.com/questions/4416391/rails-3-request-dispatch-cycle">Rails 3 request dispatch cycle</a></em></p>