How to route and render (dispatch) from a model in Ruby on Rails 3

跟風遠走 提交于 2019-12-03 20:21:18

问题


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


回答1:


It's actually even easier than that:

session = ActionDispatch::Integration::Session.new(Rails.application)
session.get(path_info)
self.body = session.response.body


来源:https://stackoverflow.com/questions/7770119/how-to-route-and-render-dispatch-from-a-model-in-ruby-on-rails-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!