Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix promotion code batch #5383

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions core/app/models/spree/promotion_code/batch_builder.rb
Original file line number Diff line number Diff line change
Expand Up @@ -39,13 +39,15 @@ def generate_random_codes
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|
codes_for_current_batch = codes_for_current_batch.map do |value|
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

collecting results of large code counts can exceed available memory pretty quickly.

Spree::PromotionCode.create!(
value: value,
promotion: promotion,
promotion_code_batch: promotion_code_batch
)
end
rescue ActiveRecord::RecordInvalid
nil
end.compact
Comment on lines +43 to +51
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To address @tvdeyen's concern, what about something like:

codes_for_current_batch.filter! do |value|
  Spree::PromotionCode.create!(
    value: value,
    promotion: promotion,
    promotion_code_batch: promotion_code_batch
  )
rescue ActiveRecord::RecordInvalid
  false
end

This should maintain the existing performance characteristics.

created_codes += codes_for_current_batch.size
end
end
Expand Down
19 changes: 19 additions & 0 deletions core/spec/models/spree/promotion_code/batch_builder_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,25 @@
subject.build_promotion_codes
expect(promotion.codes.size).to eq(number_of_codes)
end

context "when promotion_code creation returns an error" do
before do
@raise_exception = true
allow(Spree::PromotionCode).to receive(:create!) do
if @raise_exception
@raise_exception = false
raise(ActiveRecord::RecordInvalid)
else
create(:promotion_code, promotion: promotion)
end
end
end

it "creates the correct number of codes anyway" do
subject.build_promotion_codes
expect(promotion.codes.size).to eq(number_of_codes)
end
end
end
end

Expand Down