4.2 Action Dispatch: Where It All Begins
Controller and view code in Rails has always been part of its Action Pack framework. As of Rails 3, dispatching of requests was extracted into its own sub-component of Action Pack called Action Dispatch
. It contains classes that interface the rest of the controller system to Rack.
4.2.1 Request Handling
The entry point to a request is an instance of ActionDispatch::Routing::RouteSet
, the object on which you can call draw at the top of config/routes.rb.
The route set chooses the rule that matches, and calls its Rack endpoint. So a route like:
get 'foo', to: 'foo#index'
has a dispatcher instance associated to it, whose call
method ends up executing:
FooController.action(:index).call
4.2.2 Getting intimate with the Dispatcher
Just for the purpose of learning, let's trugger the Rails dispatching mechanism manuallu. We'll do this little exercise from the ground up, starting with a new Rails application:
$ rails new dispatch_me
$ cd dispatch_me
$ rails generate controller demo index
$ rails conosle
>> env = {}
>> env['REQUEST_METHOD'] = 'GET'
>> env['PATH_INFO'] = '/demo/index'
>> env['rack.input'] = StringIO.new
We’re now ready to fool the dispatcher into thinking it’s getting a request. Actually, it is getting a request. It’s just that it’s coming from someone sitting at the console, rather than from a web server:
>> rack_body_proxy = DispatchMe::Application.call(env).last
>> rack_body-proxy.last
If you want to see everything contained in the ActionDispatch::Response object returned from call then try the following code:
$ y DispatchMe::Application.call(env)
The handy y
method formats its argument as a yaml string, making it a lot easier to understand. We won’t
reproduce the output here because it’s huge.
网友评论