4. Working with Controllers - 4.2 Action Dispatch: Where It All Begins

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.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容