Skip to content

Commit

Permalink
Remove duplication by extracting methods
Browse files Browse the repository at this point in the history
  • Loading branch information
rafaelfranca committed Nov 19, 2022
1 parent 7838dba commit 2cb1ae1
Showing 1 changed file with 21 additions and 11 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -151,11 +151,11 @@ def restore!
def rollback_records
return unless records

ite = records.uniq(&:__id__)
ite = unique_records

instances_to_run_callbacks_on = prepare_instances_to_run_callbacks_on(ite)

while record = ite.shift
should_run_callbacks = record.__id__ == instances_to_run_callbacks_on[record].__id__
run_action_on_records(ite, instances_to_run_callbacks_on) do |record, should_run_callbacks|
record.rolledback!(force_restore_state: full_rollback?, should_run_callbacks: should_run_callbacks)
end
ensure
Expand All @@ -167,15 +167,14 @@ def rollback_records
def before_commit_records
return unless records

ite = records.uniq(&:__id__)

if @run_commit_callbacks
instances_to_run_callbacks_on = records.each_with_object({}) do |record, candidates|
ite = unique_records

instances_to_run_callbacks_on = ite.each_with_object({}) do |record, candidates|
candidates[record] = record
end

while record = ite.shift
should_run_callbacks = record.__id__ == instances_to_run_callbacks_on[record].__id__
run_action_on_records(ite, instances_to_run_callbacks_on) do |record, should_run_callbacks|
record.before_committed! if should_run_callbacks
end
end
Expand All @@ -184,13 +183,12 @@ def before_commit_records
def commit_records
return unless records

ite = records.uniq(&:__id__)
ite = unique_records

if @run_commit_callbacks
instances_to_run_callbacks_on = prepare_instances_to_run_callbacks_on(ite)

while record = ite.shift
should_run_callbacks = record.__id__ == instances_to_run_callbacks_on[record].__id__
run_action_on_records(ite, instances_to_run_callbacks_on) do |record, should_run_callbacks|
record.committed!(should_run_callbacks: should_run_callbacks)
end
else
Expand All @@ -209,6 +207,18 @@ def closed?; false; end
def open?; !closed?; end

private
def unique_records
records.uniq(&:__id__)
end

def run_action_on_records(records, instances_to_run_callbacks_on)
while record = records.shift
should_run_callbacks = record.__id__ == instances_to_run_callbacks_on[record].__id__

yield record, should_run_callbacks
end
end

def prepare_instances_to_run_callbacks_on(records)
records.each_with_object({}) do |record, candidates|
next unless record.trigger_transactional_callbacks?
Expand Down

0 comments on commit 2cb1ae1

Please sign in to comment.