Class: Migratrix::Loads::ActiveRecord

Inherits:
Load show all
Defined in:
lib/migratrix/loads/active_record.rb

Overview

An ActiveRecord-based Load that tries to update existing objects rather than always doing new saves. If :update is true, before saving we attempt to find the object by the primary_key column. If found, we call .update_attributes on that record instead of .save.

TODO: Verify that update_attributes still calls callbacks, e.g. validations and before_save? If not we’ll need to load the object, copy attributes manually from the transformed object, and save it.

TODO: primary_key is a bit presumptive. Would be better if it were a where clause.

Instance Attribute Summary

Attributes inherited from Load

#name, #options

Instance Method Summary collapse

Methods inherited from Load

#initialize, #transform

Constructor Details

This class inherits a constructor from Migratrix::Loads::Load

Instance Method Details

#load(transformed_objects) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/migratrix/loads/active_record.rb', line 37

def load(transformed_objects)
  transformed_objects.each do |transformed_object|
    next if seen?(transformed_object)
    if options[:update]
      object = if options[:finder]
                 options[:finder].call(transformed_object)
               elsif options[:primary_key] && options[:legacy_key]
                 transformed_object.class.where("#{options[:primary_key]}=?", transformed_object[options[:legacy_key]]).first
               end
      if object
        update_object object, transformed_object
      else
        save_object transformed_object
      end
    else
      save_object transformed_object
    end
  end
  transformed_objects
end

#save_object(transformed_object) ⇒ Object



58
59
60
61
62
63
# File 'lib/migratrix/loads/active_record.rb', line 58

def save_object(transformed_object)
  return if seen?(transformed_object)
  transformed_object.save
  seen! transformed_object
  transformed_object
end

#seenObject



21
22
23
# File 'lib/migratrix/loads/active_record.rb', line 21

def seen
  @seen ||= { }
end

#seen!(object) ⇒ Object



31
32
33
34
35
# File 'lib/migratrix/loads/active_record.rb', line 31

def seen!(object)
  if options[:cache_key]
    seen[object[options[:cache_key]]] = true
  end
end

#seen?(object) ⇒ Boolean

Returns:

  • (Boolean)


25
26
27
28
29
# File 'lib/migratrix/loads/active_record.rb', line 25

def seen?(object)
  if options[:cache_key]
    seen[object[options[:cache_key]]]
  end
end

#update_object(original_object, transformed_object) ⇒ Object



65
66
67
68
69
70
# File 'lib/migratrix/loads/active_record.rb', line 65

def update_object(original_object, transformed_object)
  return if seen?(transformed_object)
  original_object.update_attributes transformed_object.attributes
  seen! original_object
  original_object
end