Module: BuildAssociated::ClassMethods

Defined in:
lib/build_associated.rb

Instance Method Summary collapse

Instance Method Details

#build_associated(association_name) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/build_associated.rb', line 7

def build_associated association_name
  begin 
    alias_method "_#{association_name}", association_name
    remove_method(association_name)

    define_method association_name do
      obj = self.send("_#{association_name}") || super(association_name)
      obj ||= self.send("build_#{association_name}") unless self.frozen? or self.readonly?
      return obj
    end
  rescue NameError
    define_method association_name do
      obj = super(association_name)
      obj ||= self.send("build_#{association_name}") unless self.frozen? or self.readonly?
      return obj
    end
  end
end