Wednesday, November 26, 2008

I killed ApplicationController


For the longest time, developers have asked for application.rb to be renamed to application_controller.rb. This is finally fixed in RailsEdge, and there's even a Death of Application.rb blog posting about it.

That's great, but none of this affects me. Why? Because ApplicationController always annoyed me, so I killed it.


Life without ApplicationController

You might ask, "how do you survive without this loving, parental figure; the ApplicationController?" Because my parent is ActionController::Base, in the same way that most of your models inherit from ActiveRecord::Base. Can you tell me why your models don't inherit from an arbitrary ApplicationRecord class?

The primary reason why a developer puts code into ApplicationController is for code reuse and changing default behavior. The ultimate result is that this class becomes a dumping ground for any common methods required across two or more controllers. Ruby has a better pattern for reusing methods and changing behavior across classes: Modules.

I create my own controller modules in the lib folder, and include them into ActionController::Base. If I want only certain controllers to be affected, the module defines a class level method, similar to the before_filter and has_many macros. For example, some controllers require a login. Rather than adding a filter to ApplicationController, I would make a 'require_login' module. My controllers could optionally use it like this:



1
2
3
class PostController < ActionController::Base
require_login
end


Why do I go through all this trouble? Because it (1) cuts one layer out of the inheritance tree, and (2) forces me to think about packaging functionality into small, testable modules. I encourage you to look at the code in your ApplicationController, and question whether any or all of your controllers should be inheriting from it.

Friday, November 21, 2008

I am not dead


To the dedicated numbers subscribing to my blog: I'd like to notify everyone that I still exist. I just awakened from a temporary, semi-comatose state. Thankfully, I have numerous blog posts queued in my non-volatile persistence mechanism.

Please stand by for tips in perfectionism with HTTP, SQL and Ruby on Rails.