Skip to content

Commit

Permalink
Generate correct number of codes in BatchBuilder
Browse files Browse the repository at this point in the history
Previously, due to a bug in the inner loop, BatchBuilder could generate
more codes than were requested.

This removes the inner loop in favour of a single, smarter outer loop.
Instead of always creating exactly batch_size new codes, we now create
up to batch_size new codes. On each loop we try to generate batch_size
new potential codes and only save the ones which are unique.

This should result in fewer selects in scenarios where there is
contention over codes. Though this is entire system is not well suited
for there to be many conflicts.
  • Loading branch information
jhawthorn committed Feb 15, 2018
1 parent fa8f3f1 commit c905158
Showing 1 changed file with 6 additions and 8 deletions.
14 changes: 6 additions & 8 deletions core/app/models/spree/promotion_code/batch_builder.rb
Original file line number Diff line number Diff line change
Expand Up @@ -26,16 +26,13 @@ def build_promotion_codes
private

def generate_random_codes
total_batches = (number_of_codes.to_f / self.class.batch_size).ceil
created_codes = 0

total_batches.times do |i|
codes_for_current_batch = Set.new
codes_to_generate = [self.class.batch_size, number_of_codes - i * batch_size].min
while created_codes < number_of_codes
max_codes_to_generate = [self.class.batch_size, number_of_codes - created_codes].min

while codes_for_current_batch.size < codes_to_generate
new_codes = Array.new(codes_to_generate) { generate_random_code }.to_set
codes_for_current_batch += get_unique_codes(new_codes)
end
new_codes = Array.new(max_codes_to_generate) { generate_random_code }.uniq
codes_for_current_batch = get_unique_codes(new_codes)

codes_for_current_batch.each do |value|
Spree::PromotionCode.create!(
Expand All @@ -44,6 +41,7 @@ def generate_random_codes
promotion_code_batch: promotion_code_batch
)
end
created_codes += codes_for_current_batch.size
end
end

Expand Down

0 comments on commit c905158

Please sign in to comment.