What are the properties and methods of an application controller?

advertisements

I am trying to understand Rails a little deeper through the lenses of object oriented programming.

When building a basic app, the property and methods of a model seems more apparent and visual as the developer defines properties and methods like find and all are used often.

But I am not sure what property and method a controller has and what is used and when it is used.

I've thought of using the .method method to see what method the Application Controller has but I couldn't figure out what to type in the console for the object slot.

Bottomline is that I know what a controller is doing in theory but when it comes to actual source code, not sure which part of the code represents an ApplicationController.

What kind of methods and properties are used for say a simple CRUD application like a blog?


In a standard rails application, all the app's controllers are inherited from ApplicationController which inherits from ActionController::Base, which contains classes and method definitions for handling HTTP request that enters your application's codebase from the client (web-browser, bots, mobile devices, etc), extract request parameters, process data and return a response back to the client in proper format (XML, HTML, JSON, etc) as per the request.

So, from an OOP point of view, ApplicationController serves at the top of the hierarchy of all your application's controllers. Thus, most of the common filters/hooks which are required in every part of your applicaion such as: handling authentication, authorization, etc are defined here as this is the first place that the HTTP request hits on your application before delegating to the specified controller.

ApplicationController object is instantiated when there is a presence of HTTP request from a client. For example, if you have an action test on application_controller.rb with routes.rb entry get '/test' => 'application#test':

class ApplicationController < ActionController::Base

  def test
    puts "Instance: #{self}"
    puts "Instance Methods: #{self.methods}"
  end

end

You can start your local server and visit http://localhost:3000/test and check your server logs to inspect the ApplicationController object and it's methods.

For detailed inspection, I would recommend adding gem 'pry' to your Gemfile and bundling it, then using binding.pry on the ApplicationController#test action, which allows you to further inspect the object on your server on runtime.