Module: ARMerge::InstanceMethods

Defined in:
lib/ar_merge.rb

Instance Method Summary collapse

Instance Method Details

#merge!(other, options = {}) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/ar_merge.rb', line 11

def merge!(other, options={})
  raise "cannot merge wit a new record" if other.new_record?
  raise "cannot merge with myself" if other == self

  #merge associations
  (options[:associations]||[]).each do |association_name|
    other.send(association_name).each do |associated|
      send(association_name) << associated
    end
    
    #update counters, this is very basic/hacky/not secure for customized counters...
    counter = "#{association_name}_count"
    next unless other.respond_to?(counter) and respond_to?("#{counter}=")
    self.class.update_counters(id, counter => other.send(counter))
  end

  #merge attributes
  (options[:attributes]||[]).each do |attr|
    send("#{attr}=", other.send(attr)) if send(attr).blank?
  end

  #cleanup
  other.reload.destroy
  save!
end