I want to dispatch (route and render) from a model. (I only care about GET
requests and I ignore Accept:
headers, so I only look at PATH_INFO
.)
# app/models/response.rb
class Response < ActiveRecord::Base
# col :path_info
# col :app_version
# col :body, :type => :text
def set_body
params = Rails.application.routes.recognize_path(path_info, :method => :get)
controller = "#{params[:controller].camelcase}Controller".constantize.new
controller.action_name = params[:action]
controller.request = ActionDispatch::Request.new('rack.input' => [])
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
The above code works, but it feels clunky. What's the right way to do it? I'm imagining Yehuda Katz would tell me something like:
def set_body
# [...]
app = "#{params[:controller].camelcase}Controller".constantize.action(params[:action])
app.process params
self.body = app.response.body
end
FWIW here's my routes file:
# config/routes.rb
MyApp::Application.routes.draw do
resources :products # GET /products.json?merchant_id=foobar
match '/:id(.:format)' => 'contents#show', :via => 'get' # GET /examples
root :to => 'contents#index', :via => 'get' # GET /
end
See also: Rails 3 request dispatch cycle
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…