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 extension fields to API responses and model extensions (V-3735) (#14899)

Łukasz Adamczyk0686901283c1
diff --git a/docs/developer/customization/api.mdx b/docs/developer/customization/api.mdx
index 04752890cf..a65b520996 100644
--- a/docs/developer/customization/api.mdx
+++ b/docs/developer/customization/api.mdx
@@ -83,6 +83,40 @@ The brand data is available via `?expand=brand`:
GET /api/v3/store/products/prod_86Rf07xd4z?expand=brand
```
+### Adding a Field from an Extension
+
+Replacing a serializer works for your own application, but the setting holds one replacement. An extension that replaced `admin_product_serializer` would be silently undone by an application that replaces it too. An extension adds read-only fields to a core serializer instead: an **attribute**, written as it is, or an **association**, a related record or a list of them written by the extension's own serializer:
+
+```ruby server/config/initializers/my_extension.rb
+Rails.application.config.after_initialize do
+ Spree.api.extension_fields.attribute(:admin_product_serializer, method: :warranty_text)
+
+ Spree.api.extension_fields.association(
+ :admin_product_serializer,
+ one: :warranty,
+ serializer: 'MyExtension::WarrantySerializer',
+ expand: true
+ )
+
+ Spree.api.extension_fields.association(
+ :admin_product_serializer,
+ many: :warranty_claims,
+ serializer: 'MyExtension::ClaimSerializer',
+ expand: true
+ )
+end
+```
+
+- **The name** is the response key and the record's method that gives the value: `method:` for an attribute, `one:` or `many:` for an association. `one: :warranty` writes `product.warranty` with the given serializer; `many: :warranty_claims` writes each of `product.warranty_claims`. An extension adds such methods to core models with [model extensions](/developer/customization/decorators#adding-to-a-model-without-a-decorator).
+- **A simple computed value** needs no method: name the field and pass `value:`, as in `attribute(:admin_product_serializer, :warranty_months, value: ->(product) { ... })`. An association takes `value:` the same way, beside its `one:` or `many:`.
+- **Registered by dependency key**, such as `admin_product_serializer`. If the application replaces that serializer with one that inherits from a core serializer, as shown above, the field still renders on the replacement.
+- **`expand: true`** shows the field only when the request asks for it with `?expand=warranty`. Without it, the field is always shown. An association's nested expands reach its serializer, so `?expand=warranty.claims` passes `claims` on, the same way `?expand=variants.media` works. Lists apply the same expands to every item.
+- **Associations read on lists are batched** when they are Active Record associations, as core ones are. A value computed by `value:` is read for each record.
+- **Names are unique per serializer.** Registering a name that the serializer or another extension already uses raises an error at boot.
+- **Not in the generated SDK types.** The extension that adds a field declares its TypeScript type.
+
+This is the read side of [adding an attribute to a core resource](#adding-an-attribute-to-a-core-resource), which makes a field writable.
+
### Serializer Dependency Keys
Here are the most commonly customized v3 serializers:
diff --git a/docs/developer/customization/decorators.mdx b/docs/developer/customization/decorators.mdx
index 472cc36ed8..9ea84ca189 100644
--- a/docs/developer/customization/decorators.mdx
+++ b/docs/developer/customization/decorators.mdx
@@ -9,6 +9,7 @@ description: Use Spree decorators to add or modify behavior on core models, cont
- **[Events & Subscribers](/developer/core-concepts/events)** - For reacting to model changes (after save, create, update, delete)
- **[Webhooks](/developer/core-concepts/webhooks)** - For notifying external services when events occur
- **[Dependencies](/developer/customization/dependencies)** - For swapping out services, serializers, and abilities
+ - **[Model extensions](#adding-to-a-model-without-a-decorator)** - For adding methods, associations, validations, and scopes to core models
- **[Dashboard Navigation](/developer/dashboard/customization/navigation)** - For adding menu items
- **[Dashboard Slots](/developer/dashboard/customization/slots)** - For adding your own UI to an existing dashboard screen
- **[Dashboard Tables](/developer/dashboard/customization/tables)** - For customizing list views
@@ -28,15 +29,49 @@ Before reaching for a decorator, check if your use case is better served by a mo
| Add a section to a dashboard form | View decorator/override | [Slots](/developer/dashboard/customization/slots) |
| Narrow what an endpoint returns | Overriding an action | Controller decorator overriding `scope` |
| Accept a new attribute on write | Controller decorator | `Model.additional_permitted_attributes +=` |
-| Add association to core model | - | Decorator (still appropriate) |
-| Add validation to core model | - | Decorator (still appropriate) |
-| Add new method to core model | - | Decorator (still appropriate) |
+| Add association to core model | Model decorator | [Model extensions](#adding-to-a-model-without-a-decorator) |
+| Add validation or scope to core model | Model decorator | [Model extensions](#adding-to-a-model-without-a-decorator) |
+| Add new method to core model | Model decorator | [Model extensions](#adding-to-a-model-without-a-decorator) |
| Make a new column [filterable](/developer/core-concepts/search-filtering) | - | Decorator (still appropriate) |
<Info>
- Decorators are still appropriate for **structural changes** like adding associations, validations, scopes, and new methods to models. Use modern alternatives for **behavioral changes** like callbacks, hooks, and side effects.
+ Add associations, validations, scopes and new methods to core models with [model extensions](#adding-to-a-model-without-a-decorator). Use the other alternatives for **behavioral changes** like callbacks, hooks, and side effects. A decorator is left for **changing what an existing method does**, which nothing else covers.
</Info>
+## Adding to a Model Without a Decorator
+
+An extension writes an ordinary concern and registers it against the core model by name. Spree includes it in the model:
+
+```ruby server/app/models/my_extension/product_warranty.rb
+module MyExtension
+ module ProductWarranty
+ extend ActiveSupport::Concern
+
+ included do
+ has_one :warranty, class_name: 'MyExtension::Warranty', dependent: :destroy
+ scope :with_warranty, -> { joins(:warranty) }
+ end
+
+ def warranty_text
+ warranty&.summary
+ end
+ end
+end
+```
+
+```ruby server/config/initializers/my_extension.rb
+Rails.application.config.after_initialize do
+ Spree.model_extensions.add('Spree::Product', 'MyExtension::ProductWarranty')
+end
+```
+
+- **It only adds.** A concern that would replace a method, a column's attribute or an association the model already has, or one another extension added, is refused at boot with an error naming both. A decorator would overwrite it without a word. To change what an existing method does, a decorator is still the tool.
+- **The configured customer and admin user classes** are named `:customer` and `:admin_user`, since their class names vary: `Spree.model_extensions.add(:customer, 'MyExtension::CustomerWarranties')`.
+- **It survives code reloading.** Spree includes the concerns again whenever development reloads the models.
+- **`Spree.model_extensions.for('Spree::Product')`** lists what is registered for a model.
+
+A method added this way can be shown in API responses with an [extension field](/developer/customization/api#adding-a-field-from-an-extension).
+
## Overview
Spree's models, API controllers and helpers can be extended or overridden to meet your requirements using standard Ruby idioms.
diff --git a/spree/api/app/serializers/spree/api/v3/base_serializer.rb b/spree/api/app/serializers/spree/api/v3/base_serializer.rb
index 1f306d2137..0351c63660 100644
--- a/spree/api/app/serializers/spree/api/v3/base_serializer.rb
+++ b/spree/api/app/serializers/spree/api/v3/base_serializer.rb
@@ -224,6 +224,20 @@ module Spree
private
+ # Adds the fields extensions registered for this class
+ # (Spree.api.extension_fields), read from the registry on every
+ # render as Spree.ransack is, so nothing is copied onto the class. A
+ # field never replaces an attribute the serializer writes itself.
+ def attributes_to_hash(object, hash)
+ super
+ Spree.api.extension_fields.for(self.class).each do |field|
+ next if @_attributes.key?(field.name)
+
+ set_key_and_attribute_body_from(object, field.name, field.reader, hash)
+ end
+ hash
+ end
+
# Override Alba's fetch_attribute to automatically inject nested expand params
# into child serializers via nested_params.
# Uses `key` (the public API name, e.g. :categories) for expand lookup,
diff --git a/spree/api/lib/spree/api.rb b/spree/api/lib/spree/api.rb
index 831f9c0413..5f8c04c0ee 100644
--- a/spree/api/lib/spree/api.rb
+++ b/spree/api/lib/spree/api.rb
@@ -3,6 +3,7 @@ require 'pagy'
require 'typelizer'
require 'typelizer/proc_resource_resolution'
require 'typelizer/open_enums'
+require 'spree/api/extension_fields'
module Spree
module Api
@@ -40,6 +41,13 @@ module Spree
api_dependency?(base_name) || super
end
+ # Fields extensions add to core serializers' responses.
+ #
+ # @return [Spree::Api::ExtensionFields]
+ def extension_fields
+ @extension_fields ||= Spree::Api::ExtensionFields.new
+ end
+
# Direct access to raw dependencies object for backwards compatibility
def dependencies
Spree::Api::Dependencies
diff --git a/spree/api/lib/spree/api/extension_fields.rb b/spree/api/lib/spree/api/extension_fields.rb
new file mode 100644
index 0000000000..7764ce7b22
--- /dev/null
+++ b/spree/api/lib/spree/api/extension_fields.rb
@@ -0,0 +1,167 @@
+module Spree
+ module Api
+ # Read-only fields an extension adds to a core serializer's responses —
+ # the read side of +additional_permitted_attributes+.
+ #
+ # A field is registered against a serializer's dependency name, not its
+ # class, so a host app that replaces the serializer through +Spree.api+
+ # still renders it. An attribute writes its value as it is; an association
+ # renders a related record, or a list of them, with the extension's own
+ # serializer. Fields are left out of the generated SDK types: the
+ # extension that adds one declares its type.
+ #
+ # @example
+ # Spree.api.extension_fields.attribute(:admin_product_serializer, method: :warranty_text)
+ # Spree.api.extension_fields.association(
+ # :admin_product_serializer, one: :warranty,
+ # serializer: 'MyExtension::WarrantySerializer', expand: true
+ # )
+ class ExtensionFields
+ # What attributes and associations share: a name, whether it waits for
+ # an expand, and where its value comes from.
+ class Field
+ attr_reader :name
+
+ def initialize(name:, expand:, value:)
+ @name = name
+ @expand = expand
+ @value = value
+ end
+
+ # @return [Boolean] whether the field is shown only when the request expands it
+ def expand?
+ @expand
+ end
+
+ # Run inside the core serializer, so it sees the request's expands.
+ # @return [Proc]
+ def reader
+ field = self
+ @reader ||= proc do |object|
+ next Alba::REMOVE_KEY if field.expand? && !expand?(field.name)
+
+ field.render(field.value_for(object), params: nested_params(field.name))
+ end
+ end
+
+ # An extension cannot add a method to a core model, so +value+ can
+ # supply the value from the record instead.
+ #
+ # @param record [Object] the record the core serializer is writing
+ # @return [Object]
+ def value_for(record)
+ @value ? @value.call(record) : record.public_send(name)
+ end
+ end
+
+ # A value written as it is.
+ class Attribute < Field
+ # @return [Object]
+ def render(value, **)
+ value
+ end
+ end
+
+ # A related record, or a list of them, written by the extension's
+ # serializer, which also receives the request's nested expands.
+ class Association < Field
+ def initialize(serializer:, **)
+ super(**)
+ @serializer = serializer
+ end
+
+ # @return [Hash, Array<Hash>, nil]
+ def render(value, params:)
+ return if value.nil?
+
+ serializer_class.new(value, params: params).serializable_hash
+ end
+
+ private
+
+ def serializer_class
+ @serializer.is_a?(String) ? @serializer.constantize : @serializer
+ end
+ end
+
+ class DuplicateField < ArgumentError; end
+
+ def initialize
+ @fields = Hash.new { |hash, key| hash[key] = {} }
+ @class_readers = {}
+ end
+
+ # Either names the record's method that gives the value, or names the
+ # field and supplies its value:
+ #
+ # attribute(:admin_product_serializer, method: :warranty_text)
+ # attribute(:admin_product_serializer, :warranty_months, value: ->(product) { ... })
+ #
+ # @param dependency [Symbol] the serializer's dependency name, e.g. +:admin_product_serializer+
+ # @param name [Symbol, String, nil] the response key of a field whose value is given by +value+
+ # @param method [Symbol, String, nil] the response key, and the record's method that gives the value
+ # @param expand [Boolean] true to show the field only when the request expands it
+ # @param value [#call, nil] gives the value from the record; required with +name+, refused with +method+
+ # @raise [ArgumentError] when the dependency is not a serializer, or the name and value do not match up
+ # @raise [DuplicateField] when the serializer already has a field of that name
+ # @return [void]
+ def attribute(dependency, name = nil, method: nil, expand: false, value: nil)
+ raise ArgumentError, 'Pass either a name or method:' unless name.present? ^ method.present?
+ raise ArgumentError, 'A named attribute needs value:' if name.present? && value.nil?
+ raise ArgumentError, 'An attribute reading method: takes no value:' if method.present? && value
+
+ add(dependency, Attribute.new(name: (name || method).to_sym, expand: expand, value: value))
+ end
+
+ # @param dependency [Symbol] the serializer's dependency name, e.g. +:admin_product_serializer+
+ # @param serializer [Class, String] writes each related record
+ # @param one [Symbol, String, nil] the response key of a single related record, read from the record's method of that name
+ # @param many [Symbol, String, nil] the same, for a list of related records
+ # @param expand [Boolean] true to show the field only when the request expands it
+ # @param value [#call, nil] gives the related record, or records, instead of calling the method
+ # @raise [ArgumentError] when the dependency is not a serializer, or not exactly one of +one+ and +many+ is given
+ # @raise [DuplicateField] when the serializer already has a field of that name
+ # @return [void]
+ def association(dependency, serializer:, one: nil, many: nil, expand: false, value: nil)
+ raise ArgumentError, 'Pass either one: or many:' unless one.present? ^ many.present?
+
+ add(dependency, Association.new(name: (one || many).to_sym, serializer: serializer, expand: expand, value: value))
+ end
+
+ # @return [void]
+ def unregister(dependency, name)
+ @fields[dependency.to_sym].delete(name.to_sym)
+ end
+
+ # The fields of every dependency that currently resolves to this class.
+ #
+ # @param serializer_class [Class]
+ # @return [Array<Field>]
+ def for(serializer_class)
+ @fields.each_with_object([]) do |(dependency, fields), result|
+ # The dependency's cached reader, skipping Spree.api's method_missing on every render.
+ next if fields.empty? || Spree::Api::Dependencies.public_send(@class_readers[dependency]) != serializer_class
+
+ result.concat(fields.values)
+ end
+ end
+
+ private
+
+ def add(dependency, field)
+ dependency = dependency.to_sym
+ # Current names only: a pre-rename key would be resolved through its
+ # deprecation warning on every render.
+ unless dependency.to_s.end_with?('_serializer') && Spree::Api::Dependencies.class::INJECTION_POINTS.include?(dependency)
+ raise ArgumentError, "#{dependency} is not an API serializer"
+ end
+ if @fields[dependency].key?(field.name) || Spree.api.public_send(dependency)._attributes.key?(field.name)
+ raise DuplicateField, "#{dependency} already has a field named #{field.name}"
+ end
+
+ @fields[dependency][field.name] = field
+ @class_readers[dependency] ||= :"#{dependency}_class"
+ end
+ end
+ end
+end
diff --git a/spree/api/spec/lib/spree/api/extension_fields_spec.rb b/spree/api/spec/lib/spree/api/extension_fields_spec.rb
new file mode 100644
index 0000000000..0d53457af3
--- /dev/null
+++ b/spree/api/spec/lib/spree/api/extension_fields_spec.rb
@@ -0,0 +1,176 @@
+require 'spec_helper'
+
+class ExtensionFieldsSpecWarrantySerializer
+ include Alba::Resource
+
+ attribute :months do |product|
+ product.name.length
+ end
+
+ attribute :expand do
+ params[:expand]
+ end
+end
+
+RSpec.describe Spree::Api::ExtensionFields do
+ let(:registry) { described_class.new }
+ let(:store) { @default_store }
+ let(:product) { create(:product, name: 'Widget', store: store) }
+ let(:params) { { store: store, currency: 'USD' } }
+
+ before { allow(Spree.api).to receive(:extension_fields).and_return(registry) }
+
+ def render(serializer = Spree.api.admin_product_serializer, record = product, expand: nil)
+ serializer.new(record, params: params.merge(expand: expand)).to_h
+ end
+
+ describe 'an attribute' do
+ before { product.define_singleton_method(:warranty_text) { 'Two years' } }
+
+ it "writes the value of the record's method of that name" do
+ registry.attribute(:admin_product_serializer, method: :warranty_text)
+
+ expect(render['warranty_text']).to eq('Two years')
+ end
+
+ it 'takes a value supplied for its name' do
+ registry.attribute(:admin_product_serializer, :warranty_months, value: ->(record) { record.name.length })
+
+ expect(render['warranty_months']).to eq(6)
+ end
+
+ it 'is left out unless expanded, when it waits for an expand' do
+ registry.attribute(:admin_product_serializer, method: :warranty_text, expand: true)
+
+ expect(render).not_to have_key('warranty_text')
+ expect(render(expand: ['warranty_text'])['warranty_text']).to eq('Two years')
+ end
+ end
+
+ describe 'an association' do
+ context 'with one related record, shown always' do
+ before do
+ product.define_singleton_method(:warranty) { self }
+ registry.association(:admin_product_serializer, one: :warranty, serializer: ExtensionFieldsSpecWarrantySerializer)
+ end
+
+ it 'writes the related record with its own serializer' do
+ expect(render['warranty']).to include('months' => 6)
+ end
+
+ it 'drops the field once it is unregistered' do
+ render
+ registry.unregister(:admin_product_serializer, :warranty)
+
+ expect(render).not_to have_key('warranty')
+ end
+
+ it 'leaves other serializers alone' do
+ expect(render(Spree.api.product_serializer)).not_to have_key('warranty')
+ end
+
+ # The registration names the dependency, so a merchant's own serializer
+ # cannot silently drop an extension's field.
+ it 'follows a serializer the host app replaced' do
+ replacement = Class.new(Spree::Api::V3::Admin::ProductSerializer)
+ allow(Spree::Api::Dependencies).to receive(:admin_product_serializer_class).and_return(replacement)
+
+ expect(render(replacement)['warranty']).to include('months' => 6)
+ end
+ end
+
+ it 'writes a list of related records' do
+ product.define_singleton_method(:warranty_claims) { [self, self] }
+ registry.association(:admin_product_serializer, many: :warranty_claims, serializer: ExtensionFieldsSpecWarrantySerializer)
+
+ expect(render['warranty_claims'].map { |claim| claim['months'] }).to eq([6, 6])
+ end
+
+ it 'writes null when there is no related record' do
+ registry.association(:admin_product_serializer, one: :warranty, serializer: ExtensionFieldsSpecWarrantySerializer, value: ->(_record) {})
+
+ expect(render).to include('warranty' => nil)
+ end
+
+ context 'when it waits for an expand' do
+ before do
+ registry.association(:admin_product_serializer, one: :warranty, serializer: 'ExtensionFieldsSpecWarrantySerializer',
+ expand: true, value: ->(record) { record })
+ end
+
+ it 'is left out unless expanded' do
+ expect(render).not_to have_key('warranty')
+ end
+
+ it 'is shown when expanded' do
+ expect(render(expand: ['warranty'])['warranty']).to include('months' => 6, 'expand' => [])
+ end
+
+ it 'passes nested expands on to its serializer' do
+ expect(render(expand: ['warranty.extended'])['warranty']).to include('expand' => ['extended'])
+ end
+
+ it 'is shown on every item of a list' do
+ other = create(:product, name: 'Gadget', store: store)
+ rows = Spree.api.admin_product_serializer.new([product, other], params: params.merge(expand: ['warranty'])).to_h
+
+ expect(rows.map { |row| row['warranty']['months'] }).to eq([6, 6])
+ end
+ end
+ end
+
+ it "never leaks a parent serializer's field into a subclass" do
+ registry.attribute(:product_serializer, :warranty_text, value: ->(_record) { 'Two years' })
+ render(Spree.api.product_serializer)
+ subclass = Class.new(Spree::Api::V3::ProductSerializer)
+
+ expect(render(subclass)).not_to have_key('warranty_text')
+ end
+
+ describe 'registering' do
+ it 'refuses a name another extension took on that serializer, whichever kind of field' do
+ registry.attribute(:admin_product_serializer, method: :warranty)
+
+ expect do
+ registry.association(:admin_product_serializer, one: 'warranty', serializer: ExtensionFieldsSpecWarrantySerializer)
+ end.to raise_error(described_class::DuplicateField, /warranty/)
+ end
+
+ it 'refuses a name the serializer already writes' do
+ expect { registry.attribute(:admin_product_serializer, method: :name) }.to raise_error(described_class::DuplicateField)
+ end
+
+ it 'allows the same name on another serializer' do
+ registry.attribute(:admin_product_serializer, method: :warranty)
+
+ expect { registry.attribute(:seller_product_serializer, method: :warranty) }.not_to raise_error
+ end
+
+ it 'needs either a name with a value or method: for an attribute' do
+ expect { registry.attribute(:admin_product_serializer) }.to raise_error(ArgumentError, /name or method:/)
+ expect { registry.attribute(:admin_product_serializer, :warranty_text) }.to raise_error(ArgumentError, /needs value:/)
+ expect do
+ registry.attribute(:admin_product_serializer, method: :warranty_text, value: ->(_record) {})
+ end.to raise_error(ArgumentError, /takes no value:/)
+ end
+
+ it 'needs exactly one of one: and many: for an association' do
+ expect do
+ registry.association(:admin_product_serializer, serializer: ExtensionFieldsSpecWarrantySerializer)
+ end.to raise_error(ArgumentError, /one: or many:/)
+ expect do
+ registry.association(:admin_product_serializer, one: :warranty, many: :warranties, serializer: ExtensionFieldsSpecWarrantySerializer)
+ end.to raise_error(ArgumentError, /one: or many:/)
+ end
+
+ it 'refuses a pre-rename serializer name' do
+ expect { registry.attribute(:admin_stock_item_serializer, method: :bin) }.to raise_error(ArgumentError)
+ end
+
+ it 'refuses a dependency that is not a serializer' do
+ expect do
+ registry.attribute(:admin_product_presenter, method: :warranty)
+ end.to raise_error(ArgumentError, /not an API serializer/)
+ end
+ end
+end
diff --git a/spree/core/lib/spree/core.rb b/spree/core/lib/spree/core.rb
index 8da823a81c..3e54690c42 100644
--- a/spree/core/lib/spree/core.rb
+++ b/spree/core/lib/spree/core.rb
@@ -539,6 +539,16 @@ module Spree
@ransack ||= RansackConfiguration.new
end
+ # Concerns extensions add to core models, instead of decorating them.
+ #
+ # @example
+ # Spree.model_extensions.add('Spree::Product', 'MyExtension::ProductWarranty')
+ #
+ # @return [Spree::ModelExtensions]
+ def self.model_extensions
+ @model_extensions ||= ModelExtensions.new
+ end
+
class << self
# Dynamic methods for core dependencies
#
@@ -655,6 +665,7 @@ require 'spree/core/preferences/invalid_preferences'
require 'spree/core/preferences/json_conversion'
require 'spree/core/permission_configuration'
+require 'spree/core/model_extensions'
require 'spree/core/ransack_configuration'
require 'spree/core/pricing/context'
require 'spree/core/pricing/price_resolution'
diff --git a/spree/core/lib/spree/core/engine.rb b/spree/core/lib/spree/core/engine.rb
index bb1f6aae8d..b915fa70f5 100644
--- a/spree/core/lib/spree/core/engine.rb
+++ b/spree/core/lib/spree/core/engine.rb
@@ -613,6 +613,13 @@ module Spree
end
end
+ # The same contexts, for the concerns extensions add to core models.
+ initializer 'spree.model_extensions.schedule_apply', after: :load_config_initializers do |app|
+ app.config.after_initialize do
+ Spree.model_extensions.apply
+ end
+ end
+
# A hook registered against a key no workflow declares would never fire
# and never say so. Checking after eager load turns that typo into a
# boot failure. Skipped when eager loading is off (development,
@@ -630,6 +637,10 @@ module Spree
ActsAsTaggableOn::Tag.include(Spree::RansackableAttributes)
ActsAsTaggableOn::Tag.whitelisted_ransackable_attributes = %w[id name]
+ # Reloading makes new model classes, which have none of the
+ # extensions' concerns yet.
+ Spree.model_extensions.apply
+
# Reset and re-activate event subscribers on code reload
# activate! will register all subscribers from Spree.subscribers
# Note: resolve_subscriber in register_subscribers! handles stale class references
diff --git a/spree/core/lib/spree/core/model_extensions.rb b/spree/core/lib/spree/core/model_extensions.rb
new file mode 100644
index 0000000000..41989e8594
--- /dev/null
+++ b/spree/core/lib/spree/core/model_extensions.rb
@@ -0,0 +1,111 @@
+module Spree
+ # Adds an extension's own methods, associations, scopes and validations to
+ # core models without a decorator.
+ #
+ # An extension writes an ordinary concern and registers it against the
+ # model by name. Spree includes it, so the model's own methods still win:
+ # an extension adds to a model, it never replaces what the model does.
+ # A concern that would shadow a method, attribute or association the model
+ # already has is refused at boot, naming both, where a decorator would
+ # overwrite it quietly.
+ #
+ # Registrations are kept as names and included again each time code is
+ # reloaded, so development reloading keeps them.
+ #
+ # @example
+ # Spree.model_extensions.add('Spree::Product', 'MyExtension::ProductWarranty')
+ # Spree.model_extensions.add(:customer, 'MyExtension::CustomerWarranties')
+ class ModelExtensions
+ class Conflict < StandardError; end
+
+ # The configured customer and admin user classes, which an extension cannot know by name.
+ USER_MODELS = { customer: -> { Spree.customer_class }, admin_user: -> { Spree.admin_user_class } }.freeze
+
+ def initialize
+ @extensions = Hash.new { |hash, key| hash[key] = [] }
+ @prepared = false
+ end
+
+ # @param model [String, Symbol] the model's class name, e.g. +'Spree::Product'+, or +:customer+ / +:admin_user+
+ # @param extension [String, Module] the concern to include
+ # @raise [ArgumentError] for a symbol other than +:customer+ and +:admin_user+
+ # @raise [Conflict] when the concern would shadow something the model already has
+ # @return [void]
+ def add(model, extension)
+ key = key_for(model)
+ name = extension.is_a?(Module) ? extension.name : extension.to_s
+ @extensions[key] |= [name]
+ apply_to(key, name) if @prepared
+ end
+
+ # @param model [String, Symbol]
+ # @return [Array<String>] the concerns registered for the model
+ def for(model)
+ @extensions.fetch(key_for(model), []).dup
+ end
+
+ # Includes every registered concern. Spree runs it each time code is
+ # loaded; a registration made after that is included straight away.
+ #
+ # @return [void]
+ def apply
+ @prepared = true
+ @extensions.each { |key, names| names.each { |name| apply_to(key, name) } }
+ end
+
+ private
+
+ def key_for(model)
+ return model.to_s unless model.is_a?(Symbol)
+ return model if USER_MODELS.key?(model)
+
+ raise ArgumentError, "#{model} is not a model: pass its class name, or :customer or :admin_user"
+ end
+
+ def resolve(key)
+ key.is_a?(Symbol) ? USER_MODELS.fetch(key).call : key.constantize
+ end
+
+ def apply_to(key, name)
+ model = resolve(key)
+ extension = name.constantize
+ return if model.include?(extension)
+
+ refuse_shadowed_methods!(model, extension)
+ existing = model.instance_methods
+ reflections = model.reflections.dup
+ model.include(extension)
+
+ # Associations are declared in the concern's +included+ block, so they
+ # are only known once it has run: one it declared or redeclared there
+ # must not take a name the model already answers to.
+ declared = model.reflections.reject { |name, reflection| reflections[name].equal?(reflection) }.keys
+ shadowed = declared.find { |name| reflections.key?(name) || existing.include?(name.to_sym) || attribute?(model, name) }
+ raise_conflict(model, extension, shadowed) if shadowed
+ end
+
+ def refuse_shadowed_methods!(model, extension)
+ methods = extension.instance_methods(false) + extension.private_instance_methods(false)
+ taken = methods.find { |method| model.method_defined?(method) || model.private_method_defined?(method) || attribute?(model, method) }
+ raise_conflict(model, extension, taken) if taken
+
+ return unless extension.const_defined?(:ClassMethods, false)
+
+ taken = extension::ClassMethods.instance_methods(false).find { |method| model.respond_to?(method, true) }
+ raise_conflict(model, extension, taken) if taken
+ end
+
+ # Attribute methods are generated on first use, so a column is checked by
+ # name. Without a database to read the columns from, as when assets are
+ # compiled, there are none to shadow.
+ def attribute?(model, method)
+ model.attribute_names.include?(method.to_s.delete_suffix('='))
+ rescue ActiveRecord::ActiveRecordError
+ false
+ end
+
+ def raise_conflict(model, extension, method)
+ raise Conflict, "#{extension.name} would replace #{model.name}##{method}, which the model already has"
+ end
+ end
+end
diff --git a/spree/core/spec/lib/spree/core/model_extensions_spec.rb b/spree/core/spec/lib/spree/core/model_extensions_spec.rb
new file mode 100644
index 0000000000..cfec26c21c
--- /dev/null
+++ b/spree/core/spec/lib/spree/core/model_extensions_spec.rb
@@ -0,0 +1,131 @@
+require 'spec_helper'
+
+module ModelExtensionsSpecWarranty
+ extend ActiveSupport::Concern
+
+ included do
+ has_one :warranty_variant, -> { where(is_master: false) }, class_name: 'Spree::Variant', foreign_key: :product_id
+ end
+
+ class_methods do
+ def warranty_months
+ 24
+ end
+ end
+
+ def warranty_text
+ "#{name}: two years"
+ end
+end
+
+RSpec.describe Spree::ModelExtensions do
+ let(:registry) { described_class.new }
+ # A fresh class for each example, so nothing included here reaches Spree::Product itself.
+ let(:model) { Class.new(Spree::Product) }
+
+ before { stub_const('ModelExtensionsSpecProduct', model) }
+
+ def concern(&block)
+ Module.new do
+ extend ActiveSupport::Concern
+ class_eval(&block)
+ end.tap { |extension| stub_const("ModelExtensionsSpecConcern#{extension.object_id}", extension) }
+ end
+
+ it "adds the concern's methods, class methods and associations to the model" do
+ registry.add('ModelExtensionsSpecProduct', 'ModelExtensionsSpecWarranty')
+ registry.apply
+
+ expect(model.new(name: 'Tote').warranty_text).to eq('Tote: two years')
+ expect(model.warranty_months).to eq(24)
+ expect(model.reflect_on_association(:warranty_variant)).to be_present
+ end
+
+ it 'waits until Spree applies them, then adds a later registration straight away' do
+ registry.add('ModelExtensionsSpecProduct', 'ModelExtensionsSpecWarranty')
+ expect(model).not_to include(ModelExtensionsSpecWarranty)
+
+ registry.apply
+ later = concern { def warranty_code = 'W1' }
+ registry.add('ModelExtensionsSpecProduct', later.name)
+
+ expect(model).to include(ModelExtensionsSpecWarranty, later)
+ end
+
+ it 'includes a concern once however often Spree applies them' do
+ registry.add('ModelExtensionsSpecProduct', 'ModelExtensionsSpecWarranty')
+ 2.times { registry.apply }
+
+ expect(model.ancestors.count(ModelExtensionsSpecWarranty)).to eq(1)
+ end
+
+ # Code reloading replaces the model class, which then needs the concern again.
+ it 'adds the concern again to a reloaded model' do
+ registry.add('ModelExtensionsSpecProduct', 'ModelExtensionsSpecWarranty')
+ registry.apply
+ reloaded = Class.new(Spree::Product)
+ stub_const('ModelExtensionsSpecProduct', reloaded)
+
+ registry.apply
+
+ expect(reloaded).to include(ModelExtensionsSpecWarranty)
+ end
+
+ it 'resolves the configured customer class' do
+ user_class = Class.new(Spree.customer_class)
+ allow(Spree).to receive(:customer_class).and_return(user_class)
+ registry.add(:customer, 'ModelExtensionsSpecWarranty')
+ registry.apply
+
+ expect(user_class).to include(ModelExtensionsSpecWarranty)
+ expect(registry.for(:customer)).to eq(['ModelExtensionsSpecWarranty'])
+ end
+
+ it 'lists what is registered for a model' do
+ registry.add('ModelExtensionsSpecProduct', 'ModelExtensionsSpecWarranty')
+
+ expect(registry.for('ModelExtensionsSpecProduct')).to eq(['ModelExtensionsSpecWarranty'])
+ expect(registry.for('Spree::Order')).to be_empty
+ end
+
+ it 'refuses a symbol that names no configured model' do
+ expect { registry.add(:product, 'ModelExtensionsSpecWarranty') }.to raise_error(ArgumentError, /not a model/)
+ end
+
+ describe 'refusing to replace what the model has' do
+ before { registry.apply }
+
+ it 'refuses a method the model defines' do
+ clash = concern { def purchasable? = true }
+
+ expect { registry.add('ModelExtensionsSpecProduct', clash.name) }.to raise_error(described_class::Conflict, /purchasable\?/)
+ end
+
+ it 'refuses a method named like a column' do
+ clash = concern { def slug = 'mine' }
+
+ expect { registry.add('ModelExtensionsSpecProduct', clash.name) }.to raise_error(described_class::Conflict, /slug/)
+ end
+
+ it 'refuses a class method the model has' do
+ clash = concern { class_methods { def available = none } }
+
+ expect { registry.add('ModelExtensionsSpecProduct', clash.name) }.to raise_error(described_class::Conflict, /available/)
+ end
+
+ # Rails generates column methods on first use, so the column is what is checked.
+ it 'refuses an association named like a column' do
+ # Generated again on next use, as after a fresh boot.
+ Spree::Product.undefine_attribute_methods
+ clash = concern { included { has_one :promotionable, class_name: 'Spree::Variant', foreign_key: :product_id } }
+
+ expect { registry.add('ModelExtensionsSpecProduct', clash.name) }.to raise_error(described_class::Conflict, /promotionable/)
+ end
+
+ it 'refuses an association named like a method the model has' do
+ clash = concern { included { has_one :store, class_name: 'Spree::Store' } }
+
+ expect { registry.add('ModelExtensionsSpecProduct', clash.name) }.to raise_error(described_class::Conflict, /store/)
+ end
+ end
+end