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 `CalculatedAdjustments#cached_calculator` (#13400)

Damian Legawiec952d76c79f11
diff --git a/core/app/models/concerns/spree/calculated_adjustments.rb b/core/app/models/concerns/spree/calculated_adjustments.rb
index 1c60331c5a..92b374b3e0 100644
--- a/core/app/models/concerns/spree/calculated_adjustments.rb
+++ b/core/app/models/concerns/spree/calculated_adjustments.rb
@@ -6,7 +6,7 @@ module Spree
has_one :calculator, class_name: 'Spree::Calculator', as: :calculable, inverse_of: :calculable, dependent: :destroy, autosave: true
accepts_nested_attributes_for :calculator
validates :calculator, presence: true
- delegate :compute, to: :calculator
+ delegate :compute, to: :cached_calculator
scope :with_calculator, ->(calculator) { joins(:calculator).where(calculator: { type: calculator.to_s }) }
@@ -15,7 +15,7 @@ module Spree
end
def calculator_type
- calculator.class.to_s if calculator
+ cached_calculator.class.to_s if cached_calculator
end
def calculator_type=(calculator_type)
@@ -23,6 +23,16 @@ module Spree
self.calculator = klass.new if klass && !calculator.instance_of?(klass)
end
+ # Returns the calculator using Rails.cache to avoid repeated database lookups.
+ #
+ # @return [Object, nil] The calculator object (TaxRate, PromotionAction, etc.)
+ def cached_calculator
+ Rails.cache.fetch("#{cache_key_with_version}/calculator") { calculator }
+ rescue TypeError
+ # Handle objects that can't be serialized (e.g., mock objects in tests)
+ calculator
+ end
+
private
def self.model_name_without_spree_namespace