require 'active_record'
require 'action_controller'
require 'action_mailer'
require 'action_view'

# A module that defines the behavior of a class that may contain a registry
# instance.
module RegistryContainer

  # Return the registry instance in effect for this class and all subclasses.
  def registry
    self.class.registry
  end

  # The #registry=, #registry, and #register methods must be dynamically
  # added by this method because they use class variables.
  def self.included( mod )
    super
    mod.class_eval <<-EOF
      def self.registry=( reg )
        @@registry = reg
      end

      def self.registry
        @@registry
      end

      def self.register( name )
        registry.register( name ) { self }
      end
    EOF
  end

end

class ActiveRecord::Base
  include RegistryContainer

  class << self
    alias :old_inherited :inherited

    # Automatically add this class as a service to the class's registry. The
    # service will be an underscored, demodulized, symbolized version of the
    # class name.
    def inherited( klass )
      old_inherited klass
      klass.register( Inflector.underscore( Inflector.demodulize( klass.name ) ).to_sym )
    end
  end
end

class ActionController::Base
  include RegistryContainer
end

class ActionMailer::Base
  include RegistryContainer
end

class ActionView::Base
  include RegistryContainer
end
