Class: Merger::Merge

Inherits:
Object
  • Object
show all
Defined in:
lib/merger/merge.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*records) ⇒ Merge

Returns a new instance of Merge.



5
6
7
8
9
10
11
# File 'lib/merger/merge.rb', line 5

def initialize(*records)
  @options = records.extract_options!
  @options[:destroy] = true unless @options.has_key?(:destroy)
  records = records.flatten.uniq
  @keep = options[:keep] || records.sort_by(&:id).first
  @duplicates = records - [@keep]
end

Instance Attribute Details

#duplicatesObject (readonly)

Returns the value of attribute duplicates.



3
4
5
# File 'lib/merger/merge.rb', line 3

def duplicates
  @duplicates
end

#keepObject (readonly)

Returns the value of attribute keep.



3
4
5
# File 'lib/merger/merge.rb', line 3

def keep
  @keep
end

#optionsObject (readonly)

Returns the value of attribute options.



3
4
5
# File 'lib/merger/merge.rb', line 3

def options
  @options
end

Instance Method Details

#associations!Object



22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/merger/merge.rb', line 22

def associations!
  keep.class.reflect_on_all_associations.each do |association|
    duplicates.each do |record|
      next if ignored_associations.include?(association.name)
      case association.macro
      when :has_many, :has_and_belongs_to_many
        name = "#{association.name.to_s.singularize}_ids"
        keep.send("#{name}=", keep.send(name) | record.send(name))
      when :belongs_to, :has_one
        keep.send("#{association.name}=", record.send(association.name)) if keep.send("#{association.name}").nil?
      end
    end
  end
end

#ignored_associationsObject



13
14
15
16
17
18
19
20
# File 'lib/merger/merge.rb', line 13

def ignored_associations
  return @ignored if @ignored
  @ignored = Array(options[:skip_association])
  keep.class.reflect_on_all_associations.each do |association|
    @ignored << association.through_reflection.name if association.through_reflection
  end
  @ignored
end

#merge!Object



37
38
39
40
41
42
43
44
45
# File 'lib/merger/merge.rb', line 37

def merge!
  keep.class.transaction do
    duplicates.each {|duplicate| duplicate.send(:before_merge, keep) if duplicate.respond_to?(:before_merge) }
    associations!
    duplicates.each {|duplicate| duplicate.send(:after_merge, keep) if duplicate.respond_to?(:after_merge) }
    
    duplicates.each(&:destroy) if options[:destroy]
  end
end