Skip to content

armgit / spree

Public Imported from GitHub
0

Open Source Platform for DTC, B2B Commerce, Marketplaces & Omnichannel. REST APIs, TypeScript SDKs, and production-ready Next.js storefront. Self-host it. Own your data. No vendor lock-in. Zero platform fees.

Added handy methods to the Wishlist model (#12057)

Damian Legawiec4810b8793d01
diff --git a/core/app/models/spree/wishlist.rb b/core/app/models/spree/wishlist.rb
index 679afdba8c..c9c1748c04 100644
--- a/core/app/models/spree/wishlist.rb
+++ b/core/app/models/spree/wishlist.rb
@@ -15,6 +15,8 @@ module Spree
belongs_to :store, class_name: 'Spree::Store'
has_many :wished_items, class_name: 'Spree::WishedItem', dependent: :destroy
+ has_many :variants, through: :wished_items, source: :variant, class_name: 'Spree::Variant'
+ has_many :products, -> { distinct }, through: :variants, source: :product, class_name: 'Spree::Product'
after_commit :ensure_default_exists_and_is_unique
validates :name, :store, :user, presence: true
@@ -27,6 +29,13 @@ module Spree
token
end
+ # returns the number of wished items in the wishlist
+ #
+ # @return [Integer]
+ def wished_items_count
+ @wished_items_count ||= variant_ids.count
+ end
+
def self.get_by_param(param)
find_by(token: param)
end
diff --git a/core/spec/models/spree/wishlist_spec.rb b/core/spec/models/spree/wishlist_spec.rb
index fbd12b72f6..532990f493 100644
--- a/core/spec/models/spree/wishlist_spec.rb
+++ b/core/spec/models/spree/wishlist_spec.rb
@@ -96,4 +96,31 @@ describe Spree::Wishlist, type: :model do
end.to change(Spree::WishedItem, :count).by(-1)
end
end
+
+ describe '#product_ids' do
+ let(:product) { create(:product) }
+ let(:variant) { create(:variant, product: product) }
+ let(:variant_2) { create(:variant, product: product) }
+
+ before do
+ wishlist.wished_items << create(:wished_item, variant: variant)
+ wishlist.wished_items << create(:wished_item, variant: variant_2)
+ end
+
+ it 'returns the product ids' do
+ expect(wishlist.product_ids).to eq [product.id]
+ end
+ end
+
+ describe '#wished_items_count' do
+ let(:variant) { create(:variant) }
+
+ before do
+ wishlist.wished_items << create(:wished_item, variant: variant)
+ end
+
+ it 'returns the wished items count' do
+ expect(wishlist.wished_items_count).to eq 1
+ end
+ end
end