Monday, September 8, 2008

Making methods available to helpers

I recently followed the instructions here to help set up restful authentication on an application. As part of the process an 'authenticated_system.rb' file is added to the 'lib' folder containing the module 'AuthenticatedSystem'. This is then included in the application with the line
 class ApplicationController < ActionController::Base
...
include AuthenticatedSystem


I wanted some of my views to change depending on whether on not someone was logged in as an admin. The module provided me with a logged_in? function that I could use like this to check if someone was logged_in so I thought it would be pretty straight-forward. I dutifully created an admin? function in the AuthenticatedSystem module and tried to use it in my views/helpers. Unfortunately this gave me the following error:
undefined method `admin?' for #


It turned out what I was missing was the equivalent to this:

# Inclusion hook to make #current_user and #logged_in?
# available as ActionView helper methods.
def self.included(base)
base.send :helper_method, :current_user, :logged_in?
end


I think what is happening here is that we're actually modifying (adding methods to) the base instance of the class we're being placed into (presumably ActionController::Base). Normally when including a module the methods are just added to the current class. Somehow the methods in ActionController::Base seem to be available to the Helpers/Views (ie find their way into ActionView) whereas those just added to the ApplicationController don't.

No comments: