Module: AAN::AssociationAsName::ClassMethods

Defined in:
lib/a_a_n/association_as_name.rb

Instance Method Summary collapse

Instance Method Details

#acts_as_aan(&block) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# 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