Wednesday, July 22, 2009

Rails: Forcing a Controller to have a Comment

I'm using acl_system2 for authorization. As a general rule, I think apps should deny access to everything, and then open up permissions where appropriate. However, acl_system2 makes it hard to restrict permissions in ApplicationController and open them up in each subclass.

That means I have to remember to control access in each controller. acl_system2 will allow access unless you tell it not to. That could lead to accidents. Hence, I started with the following in ApplicationController:
# === Access controls
#
# Each controller is responsible for enforcing access controls properly. It
# should either have some variation of::
#
# before_filter :require_user
# access_control :DEFAULT => 'admin'
#
# Or at the very least::
#
# # No access control is required:
# # before_filter :require_user
# # access_control :DEFAULT => 'admin'
#
# See http://github.com/ezmobius/acl_system2/tree/master for more details.
Of course, that's just a comment which no one will ever read anyway. Hence, I wrote a RSpec test to enforce it:
context "Controllers" do
controllers = Dir[File.expand_path(File.dirname(__FILE__) + "/../app/controllers/*.rb")]
it "should not be empty" do
controllers.should_not be_empty
end
controllers.each do |f|
contents = IO.read(f)

context f do
it %{should contain "before_filter :require_user" at least in a comment (see application_controller.rb)} do
contents.should =~ /before_filter :require_user/
end
it %{should contain "access_control :DEFAULT => 'admin'" at least in a comment (see application_controller.rb)} do
contents.should =~ /access_control :DEFAULT => 'admin'/
end
end
end
end
Conceptually, what's going on is that I have an interface that I want child classes to follow. Part of that interface is that you must at least provide a comment about why you don't have to require access control. Funky!

No comments: