March 2nd, 2009

Reflection

module ActiveRecord
  module ModelHelper
    def self.included(base)
      base.class_eval do
        # This creates class methods that allow me to delve into my associations
        # I can call stuff like reflect_on_has_many and it will return Class names of my has_many associations
   # I can then use them to do whatever i like.
 
        (class << self;self;end).class_eval do
 
          [:has_and_belongs_to_many, :has_one, :has_many].each do |association_sym|
              define_method "reflect_on_#{association_sym.to_s}".to_sym do
                results = self.reflect_on_all_associations.collect do |association|
                  if association.macro == association_sym
                    Class.const_get(association.class_name)
                  end
                 end
                return results.compact
              end
          end
        end
      end
    end
  end
end

Leave a Reply