Understanding Controllers in Ruby-on-Rails
(Page 1 of 4 )
In an MVC based web application, it is the controller that orchestrates and controls the flow of application logic. So to create an efficient, scalable and robust application, the clear understanding of the controller component provided by the framework is necessary. RoR is no exception.
The Controller component provided by RoR is the ActionController. In this discussion I will focus on the ActionController. The first sections will cover the services provided by ActionController and the techniques to access them. The final section will provide insight into using these techniques in the real world. So let's get started.
Into the World of the ActionController
In RoR, the Action Pack forms the core of the framework. It contains two modules, the ActionView and the ActionController. One aspect of the Action Pack is that it cannot be used as a part of anything but a web application. With this in mind let's look at what happens when a URL such as http://localhost:3000/demo/say/hello is called. As discussed in the previous article, a URL consists of the application name, then the controller name and finally the action name. So what RoR really does when a URL is typed in can be divided into the following steps :
- It loads the file say_controller.rb situated in the app/controllers directory. It happens only once in a production environment.
- Then RoR instantiates an object of the class named SayController.
- Once the class has been instantiated, it looks into app/helpers for a file named say_helper.rb. If it exists, it is loaded and the module SayHelper is mixed into the SayController object. That means the methods of the SayHelper module will be available directly from within the instantiated object of SayController.
- It then loads the model from say.rb within the app/models if found.
Now that the sequence of application initialization is cleared, let's move on to the services provided by the ActionController. The usage of the services will be discussed in detail in the future. The Controller component of the RoR provides the following services:
- Routing the requests
- Session tracking
- Filtering and Verification
- Caching
The next obvious question would be "why are all these services provided by the Controller component?" The answer lies with the fact that in an MVC based architecture, the Controller sits at the boundary of the application. Hence it can monitor every kind of data flow within the application and redirect or reroute if required. Many of these "flows" require the tracking of the details of the current user, caching the generated data for performance enhancements, and so on. So the best component to provide these services is the Controller. With that, here are the details.
Next: Routing the Requests, and Session Tracking >>
More Ruby-on-Rails Articles
More By APRajshekhar