Class: FixtureKit::ActiveRecordCoder

Inherits:
Coder
  • Object
show all
Defined in:
lib/fixture_kit/coders/active_record_coder.rb

Constant Summary collapse

EVENT =
"sql.active_record"
NAME_PATTERN =
/\A(?<model_name>.+?) (?:(?:Bulk )?(?:Insert|Upsert)|Create|Destroy|(?:Update|Delete)(?: All)?)\z/

Instance Method Summary collapse

Methods inherited from Coder

#encode

Instance Method Details

#decode(data) ⇒ Object



39
40
41
42
43
# File 'lib/fixture_kit/coders/active_record_coder.rb', line 39

def decode(data)
  data.transform_keys do |model_name|
    ActiveSupport::Inflector.constantize(model_name)
  end
end

#generate(parent_data: nil, &block) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/fixture_kit/coders/active_record_coder.rb', line 11

def generate(parent_data: nil, &block)
  captured_models = Set.new
  subscriber = lambda do |_event_name, _start, _finish, _id, payload|
    name = payload[:name].to_s
    model_name = name[NAME_PATTERN, :model_name]
    next unless model_name

    captured_models.add(ActiveSupport::Inflector.constantize(model_name))
  end

  ActiveSupport::Notifications.subscribed(subscriber, EVENT, monotonic: true, &block)

  captured_models.map! { |model| base_table_model(model) }
  captured_models.merge(parent_data.keys) if parent_data

  generate_statements(captured_models)
end

#mount(data) ⇒ Object



29
30
31
32
33
34
35
36
37
# File 'lib/fixture_kit/coders/active_record_coder.rb', line 29

def mount(data)
  statements_by_connection(data).each do |connection, statements|
    connection.disable_referential_integrity do
      # execute_batch is private in current supported Rails versions.
      # This should be revisited when Rails 8.2 makes it public.
      connection.__send__(:execute_batch, statements, "FixtureKit Load")
    end
  end
end