Class: Lockbox::Migrator

Inherits:
Object
  • Object
show all
Defined in:
lib/lockbox/migrator.rb

Instance Method Summary collapse

Constructor Details

#initialize(model) ⇒ Migrator

Returns a new instance of Migrator.



3
4
5
# File 'lib/lockbox/migrator.rb', line 3

def initialize(model)
  @model = model
end

Instance Method Details

#migrate(restart:) ⇒ Object



7
8
9
10
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
36
37
38
39
40
41
42
43
44
# File 'lib/lockbox/migrator.rb', line 7

def migrate(restart:)
  model = @model

  # get fields
  fields = model.lockbox_attributes.select { |k, v| v[:migrating] }

  # get blind indexes
  blind_indexes = model.respond_to?(:blind_indexes) ? model.blind_indexes.select { |k, v| v[:migrating] } : {}

  # build relation
  relation = model.unscoped

  unless restart
    attributes = fields.map { |_, v| v[:encrypted_attribute] }
    attributes += blind_indexes.map { |_, v| v[:bidx_attribute] }

    if defined?(ActiveRecord::Base) && model.is_a?(ActiveRecord::Base)
      attributes.each_with_index do |attribute, i|
        relation =
          if i == 0
            relation.where(attribute => nil)
          else
            relation.or(model.unscoped.where(attribute => nil))
          end
      end
    end
  end

  if relation.respond_to?(:find_each)
    relation.find_each do |record|
      migrate_record(record, fields: fields, blind_indexes: blind_indexes, restart: restart)
    end
  else
    relation.all.each do |record|
      migrate_record(record, fields: fields, blind_indexes: blind_indexes, restart: restart)
    end
  end
end