What does #self.included(base) do in Ruby on Rails' Restful Authentication?

nonopolarity picture nonopolarity · Mar 1, 2011 · Viewed 38.2k times · Source

I thought we would do

helper_method :current_user, :logged_in?, :authorized?

to make these controller methods available for use as helper methods in views. But in Restful Authentication's lib/authenticated_system.rb, I see:

# 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?, :authorized? if base.respond_to? :helper_method
end

Why is it done this way instead of that single line? Also, I don't see included being called anywhere.

Answer

nathanvda picture nathanvda · Mar 1, 2011

The self.included function is called when the module is included. It allows methods to be executed in the context of the base (where the module is included).

More info: a ruby mixin tutorial.