Class: ActiveRecord::Conversion

Inherits:
Object
  • Object
show all
Defined in:
lib/activerecord/conversion.rb,
lib/activerecord/conversion/version.rb

Constant Summary collapse

VERSION =
"0.0.1"

Class Attribute Summary collapse

Class Method Summary collapse

Class Attribute Details

.sourceObject

Returns the value of attribute source.



9
10
11
# File 'lib/activerecord/conversion.rb', line 9

def source
  @source
end

.targetObject

Returns the value of attribute target.



9
10
11
# File 'lib/activerecord/conversion.rb', line 9

def target
  @target
end

Class Method Details

.convert(source_item) ⇒ Object



57
58
59
# File 'lib/activerecord/conversion.rb', line 57

def convert source_item
  raise "implement self.convert in your subclass"
end

.create_record_tableObject



32
33
34
35
36
37
# File 'lib/activerecord/conversion.rb', line 32

def create_record_table
  record_class.connection.execute(
    "CREATE TABLE IF NOT EXISTS '#{record_table_name}'('id' INTEGER, "+
    "'#{source_foreign_key}' INTEGER, '#{target_foreign_key}' INTEGER, "+
    "PRIMARY KEY('#{source_foreign_key}'))")
end

.define_relation_to(model) ⇒ Object



39
40
41
42
# File 'lib/activerecord/conversion.rb', line 39

def define_relation_to(model)
  record_class.belongs_to(model)
  record_class.validates(model, presence: true)
end

.define_relationsObject



44
45
46
47
48
49
# File 'lib/activerecord/conversion.rb', line 44

def define_relations
  [source, target].each do |relation|
    model_name = relation.singularize
    define_relation_to(model_name)
  end
end

.migrate(source_item) ⇒ Object



61
62
63
64
65
# File 'lib/activerecord/conversion.rb', line 61

def migrate source_item
  target_item = convert(source_item)
  progress_record = record_class.create!({ source_foreign_key => source_item.id,
                                           target_foreign_key => target_item.id })
end

.record_classObject



21
22
23
24
25
26
# File 'lib/activerecord/conversion.rb', line 21

def record_class
  this = self
  @record_class ||= Class.new(ActiveRecord::Base) do
    self.table_name = this.record_table_name
  end
end

.record_table_nameObject



28
29
30
# File 'lib/activerecord/conversion.rb', line 28

def record_table_name
  self.to_s.tableize.singularize
end

.remaining_itemsObject



51
52
53
54
55
# File 'lib/activerecord/conversion.rb', line 51

def remaining_items
  source_class.where(
    ["#{source_class.primary_key} NOT IN (SELECT #{source_foreign_key} FROM :records)",
     records: record_table_name])
end

.resumeObject



67
68
69
70
71
72
73
# File 'lib/activerecord/conversion.rb', line 67

def resume
  remaining_items.each do |source_item|
    ActiveRecord::Base.transaction do
      migrate source_item
    end
  end
end

.runObject



75
76
77
78
79
# File 'lib/activerecord/conversion.rb', line 75

def run
  define_relations
  create_record_table
  resume
end