module AAN::AssociationAsName::ClassMethods

Public Instance Methods

acts_as_aan(&block) click to toggle source
# File lib/a_a_n/association_as_name.rb, line 23
      def acts_as_aan &block
        AAN::Keeper.associations(self, &block)

        AAN::Keeper.structure[self].each_pair do |association, assoc_attrs|
          assoc_attrs.each do |structure|
            attribute = structure.first
            aliased_method = structure.last
            class_eval <<EOF
              # Could not use delegate for that, since attribute and aliased method could have different names
              def #{aliased_method}
                @#{aliased_method} ||= self.send(:#{association}).try(:#{attribute})
              end

              def #{aliased_method}=(value)
                @#{aliased_method} = nil
                self.send(:#{association}_id=, association(:#{association}).klass.find_by_#{attribute}(value).try(:id))
              end
EOF
          end
        end

      end