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.
Ruby b2b-commercee-commerceecommerceecommerce-apiecommerce-frameworkecommerce-platformheadlessheadless-commerceheadless-ecommercemarketplacemulti-tenantmulti-vendormulti-vendor-ecommerceopen-sourcespree-commerce
Changed preference casting and exposed settings to match Rails' has_json
Damian Legawiec8f92225c4eee
diff --git a/docs/developer/customization/model-preferences.mdx b/docs/developer/customization/model-preferences.mdxindex 45621bd259..276f526820 100644--- a/docs/developer/customization/model-preferences.mdx+++ b/docs/developer/customization/model-preferences.mdx@@ -95,7 +95,9 @@ The SDKs also type the settings of every type Spree ships. `TypedPromotionRule`A write is checked against the schema before anything is saved. An unknown key, a value of the wrong type, a value outside `choices`, or an id of the wrong model or another store is refused with a `422` whose `code` is `invalid_preferences`; `details` names each failing value by its JSON pointer, such as `/preferences/channel_ids/1`. A secret reads back masked; sending the masked value back keeps the stored secret, and `null` clears it.-Settings of a single resource, such as the store's, are read and written under their plain names (`guest_checkout`, `timezone`), never the `preferred_` methods. A model gives a preference that name with `exposes_preferences :guest_checkout, :timezone`; the API controller still lists what it accepts.+Settings of a single resource, such as the store's, are read and written under their plain names (`guest_checkout`, `timezone`), never the `preferred_` methods. A model gives a preference that name with `exposes_preferences :guest_checkout, :timezone`, which defines `guest_checkout`, `guest_checkout=` and `guest_checkout?`; the API controller still lists what it accepts.++Strings, integers and booleans are cast the way Rails casts attributes (`"1"`, `"true"` and `"on"` are true; `"42"` is 42). A blank value is `nil` for a `nullable: true` preference, and the type's empty value otherwise.## Accessing Model Preferencesdiff --git a/docs/plans/6.0-typed-preferences.md b/docs/plans/6.0-typed-preferences.mdindex b7a36a25d2..5504fe991b 100644--- a/docs/plans/6.0-typed-preferences.md+++ b/docs/plans/6.0-typed-preferences.md@@ -68,6 +68,8 @@ Preferences reach the API in two ways, and both expose the Ruby preferences DSL- **Values stored before the declarations were typed read back in the declared form,** so a delivery method saved with numeric `amounts` can be re-saved unchanged.- **Validation errors on an exposed setting use its plain name.** A model validates `preferred_<name>`; the API reports the error as `<name>`.- **`preference_attributes Model, :name, …` in serializers** types each exposed setting from its declaration, so the generated SDK types follow the model. Store decimal settings are now exact strings.+- **Calculators are typed in the SDKs' generated resource types** (decided 2026-10-09 with the author): `calculator` is `TypedDeliveryCalculator | null` and `TypedPromotionCalculator | null`, generated through the serializers' type hints. Each settings shape is emitted as a `type` rather than an `interface`, so it stays assignable to the `Record<string, unknown>` that generic forms take.+- **Aligned with Rails 8.2's `has_json` where it costs little** (decided 2026-10-09 with the author). Storage is already the same flat JSON object; strings, integers and booleans now cast through `ActiveModel::Type`, as `has_json` does; and `exposes_preferences` defines the reader, writer and `?` predicate `has_delegated_json` would. No migration to `has_json` is planned: it covers only those three types, with no decimals, lists, secrets, nullability or published schema.- **`ItemTotal`'s `operator_min`/`operator_max` declare no `choices:` yet.** Their defaults are `>`/`<` while the code compares against `gt`/`gte`; fixing that needs a data upgrade for stored rules and is left for a follow-up.## Design Detailsdiff --git a/spree/core/lib/spree/core/preferences/preferable.rb b/spree/core/lib/spree/core/preferences/preferable.rbindex 2eb638c421..a3e934898b 100644--- a/spree/core/lib/spree/core/preferences/preferable.rb+++ b/spree/core/lib/spree/core/preferences/preferable.rb@@ -19,6 +19,8 @@ module Spree::Preferences::Preferableextend ActiveSupport::ConcernBOOLEAN_TYPE = ActiveModel::Type::Boolean.new+ INTEGER_TYPE = ActiveModel::Type::Integer.new+ STRING_TYPE = ActiveModel::Type::String.newincluded doserialize :preferences, coder: Spree::Metadata::HashSerializer@@ -347,15 +349,21 @@ module Spree::Preferences::Preferableendend+ def blank_preference_value?(value)+ value.nil? || (value.respond_to?(:empty?) && value.empty?)+ end+def convert_preference_value(value, type, nullable: false)case type+ # Strings, integers and booleans cast the way Rails casts attributes (and+ # `has_json` its keys). Our own rule on top: a blank value stays nil for a+ # nullable preference, so it can fall back to another, and becomes the+ # type's empty value otherwise.when :string, :text- # A nullable string keeps "unset" (nil / empty string) as nil so it can- # fall back to another value, instead of collapsing it to "".- if nullable && (value.nil? || (value.respond_to?(:empty?) && value.empty?))- nil+ if blank_preference_value?(value)+ nullable ? nil : ''else- value.to_s+ STRING_TYPE.cast(value)endwhen :passwordvalue.to_s@@ -366,23 +374,17 @@ module Spree::Preferences::Preferabledecimal_value ||= 0 unless nullabledecimal_value.nil? ? nil : Spree::Money::Rounding.parse_decimal(decimal_value)when :integer- int_value = value.presence- int_value ||= 0 unless nullable- int_value.present? ? int_value.to_i : int_value+ if blank_preference_value?(value)+ nullable ? nil : 0+ else+ INTEGER_TYPE.cast(value) || 0+ endwhen :boolean- # A nullable boolean keeps "unset" (nil / empty string) as nil so it can- # fall back to another value, instead of collapsing it to false. An- # explicit false is preserved (it is neither nil nor empty).- if nullable && (value.nil? || (value.respond_to?(:empty?) && value.empty?))- nil- elsif value.is_a?(FalseClass) ||- value.nil? ||- value == 0 ||- value&.to_s =~ /^(f|false|0)$/i ||- (value.respond_to?(:empty?) && value.empty?)- false+ # An explicit false is kept: it is neither nil nor empty.+ if blank_preference_value?(value)+ nullable ? nil : falseelse- true+ BOOLEAN_TYPE.cast(value)endwhen :arrayvalue.is_a?(Array) ? value : Array.wrap(value)diff --git a/spree/core/lib/spree/core/preferences/preferable_class_methods.rb b/spree/core/lib/spree/core/preferences/preferable_class_methods.rbindex a51dc95ad0..640933566c 100644--- a/spree/core/lib/spree/core/preferences/preferable_class_methods.rb+++ b/spree/core/lib/spree/core/preferences/preferable_class_methods.rb@@ -133,8 +133,10 @@ module Spree::Preferencesendend- # Gives each named preference a plain reader and writer, so the API reads- # and writes `guest_checkout` rather than the DSL's `preferred_guest_checkout`.+ # Gives each named preference a plain reader, writer and predicate, so the+ # API reads and writes `guest_checkout` rather than the DSL's+ # `preferred_guest_checkout` — the methods Rails' `has_delegated_json`+ # defines, so callers would not change if the storage ever moved to it.# Grants no write access: each API controller still lists what it permits.## exposes_preferences :guest_checkout, :timezone@@ -149,6 +151,9 @@ module Spree::Preferencesdefine_method(name) { public_send(:"preferred_#{name}") }define_method(:"#{name}=") { |value| public_send(:"preferred_#{name}=", value) }+ # As `has_json` defines one; a predicate the model already has (one+ # that falls back to another setting, say) is kept.+ define_method(:"#{name}?") { public_send(:"preferred_#{name}").present? } unless method_defined?(:"#{name}?")endself.exposed_preference_names = (exposed_preference_names | names.map(&:to_sym)).freezeenddiff --git a/spree/core/spec/models/spree/preferences/preferable_spec.rb b/spree/core/spec/models/spree/preferences/preferable_spec.rbindex 592b9fa807..bfb37b6e36 100644--- a/spree/core/spec/models/spree/preferences/preferable_spec.rb+++ b/spree/core/spec/models/spree/preferences/preferable_spec.rb@@ -473,10 +473,22 @@ describe Spree::Preferences::Preferable, type: :model doit 'exposes a preference under its plain name' doexpect(record.flavor).to eq('vanilla')+ expect(record.flavor?).to be(true)record.flavor = 'mint'expect(record.preferred_flavor).to eq('mint')end+ it 'casts strings, integers and booleans the way Rails casts attributes' do+ preferable_class.preference :enabled, :boolean, default: true+ preferable_class.preference :limit, :integer, default: 1++ record.set_preference(:enabled, 'off')+ record.set_preference(:limit, '42')++ expect(record.preferred_enabled).to be(false)+ expect(record.preferred_limit).to eq(42)+ end+it 'refuses to expose a name that is not a preference or is already a method' doexpect { preferable_class.exposes_preferences :not_declared }.to raise_error(ArgumentError, /no preference/)expect { preferable_class.exposes_preferences :flavor }.to raise_error(ArgumentError, /a method of that name exists/)