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



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/a_a_n/association_as_name.rb', line 25

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
        attr_accessor :#{aliased_method}
        before_validation :aan_set_#{association}
        after_initialize :aan_set_#{aliased_method}

        def #{aliased_method}
          @#{aliased_method} ||= #{association}.try(:#{attribute})
        end

        def #{association}_with_aan_assigment=(new_object)
          #{AAN::Keeper.nullify_aliased_methods_for self, association}
          association(:#{association}).replace(new_object)
        end
        alias_method_chain :#{association}=, :aan_assigment

        protected

        def aan_set_#{association}
          unless #{aliased_method}.blank?
            obj = association(:#{association}).klass.find_by_#{attribute} #{aliased_method}
            self.#{association} = obj unless obj.nil?
          end
        end

        def aan_set_#{aliased_method}
          unless #{aliased_method}.blank?
            obj = association(:#{association}).klass.find_by_#{attribute} #{aliased_method}
            self.#{association} = obj unless obj.nil?
          end
        end
EOF
    end
  end

end