Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
489 views
in Technique[技术] by (71.8m points)

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It's actually even easier than that:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...