本文介绍了如何在 Ruby on Rails 3 中从模型路由和渲染(调度)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想从模型中调度(路由和渲染).(我只关心 GET
请求而忽略 Accept:
标头,所以我只看 PATH_INFO
.)
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
上面的代码工作,但感觉很笨拙.正确的方法是什么?我在想象 Yehuda Katz 会告诉我这样的事情:
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 这是我的路线文件:
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
另请参阅:Rails 3 请求调度周期
推荐答案
其实比这更简单:
session = ActionDispatch::Integration::Session.new(Rails.application)
session.get(path_info)
self.body = session.response.body
这篇关于如何在 Ruby on Rails 3 中从模型路由和渲染(调度)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!