Class: BulkDependencyEraser::Nullifier

Inherits:
Base
  • Object
show all
Defined in:
lib/bulk_dependency_eraser/nullifier.rb

Constant Summary collapse

DEFAULT_OPTS =
{
  verbose: false,
  db_nullify_wrapper: self::DEFAULT_DB_WRAPPER
}.freeze

Constants inherited from Base

Base::DEFAULT_DB_WRAPPER

Instance Attribute Summary

Attributes inherited from Base

#errors

Instance Method Summary collapse

Constructor Details

#initialize(class_names_columns_and_ids:, opts: {}) ⇒ Nullifier

  • structure:

    {
      <model_name>: {
        column_name: <array_of_ids>
      }
    }
    

Parameters:

  • class_names_columns_and_ids (Hash)
    • model names with columns to nullify pointing towards the record IDs that require the nullification.

  • opts (Hash) (defaults to: {})
    • hash of options, allowlisted in DEFAULT_OPTS



16
17
18
19
# File 'lib/bulk_dependency_eraser/nullifier.rb', line 16

def initialize class_names_columns_and_ids:, opts: {}
  @class_names_columns_and_ids = class_names_columns_and_ids
  super(opts:)
end

Instance Method Details

#executeObject



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/bulk_dependency_eraser/nullifier.rb', line 21

def execute
  ActiveRecord::Base.transaction do
    current_class_name = 'N/A'
    current_column = 'N/A'
    begin
      class_names_columns_and_ids.keys.reverse.each do |class_name|
        current_class_name = class_name
        klass = class_name.constantize

        columns_and_ids = class_names_columns_and_ids[class_name]

        columns_and_ids.each do |column, ids|
          current_column = column
          # Disable any ActiveRecord::InvalidForeignKey raised errors.
          # src https://stackoverflow.com/questions/41005849/rails-migrations-temporarily-ignore-foreign-key-constraint
          #     https://apidock.com/rails/ActiveRecord/ConnectionAdapters/AbstractAdapter/disable_referential_integrity
          ActiveRecord::Base.connection.disable_referential_integrity do
            nullify_in_db do
              klass.unscoped.where(id: ids).update_all(column => nil)
            end
          end
        end
      end
    rescue Exception => e
      report_error("Issue attempting to nullify '#{current_class_name}' column '#{current_column}': #{e.name} - #{e.message}")
      raise ActiveRecord::Rollback
    end
  end

  return errors.none?
end