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.

Make `Spree::Event` an ActiveModel class

Damian Legawiec8d7c0d81e09c
diff --git a/core/app/models/spree/event.rb b/core/app/models/spree/event.rb
index 5655eeb21b..f31ef45ab9 100644
--- a/core/app/models/spree/event.rb
+++ b/core/app/models/spree/event.rb
@@ -5,6 +5,7 @@ module Spree
#
# Events are immutable objects that carry information about something
# that happened in the system. They contain:
+ # - An id (UUID)
# - A name (e.g., 'order.complete', 'product.create')
# - A payload (serialized data about the event)
# - Metadata (contextual information like store_id, timestamps)
@@ -16,33 +17,45 @@ module Spree
# )
#
# @example Accessing event data
- # event.name # => 'order.complete'
- # event.payload # => { 'id' => 1, 'number' => 'R123456' }
- # event.timestamp # => 2024-01-15 10:30:00 UTC
+ # event.id # => "550e8400-e29b-41d4-a716-446655440000"
+ # event.name # => 'order.complete'
+ # event.payload # => { 'id' => 1, 'number' => 'R123456' }
+ # event.created_at # => 2024-01-15 10:30:00 UTC
#
class Event
- attr_reader :name, :payload, :metadata, :timestamp
+ include ActiveModel::Model
+ include ActiveModel::Attributes
+ include ActiveModel::Serializers::JSON
+
+ attribute :id, :string
+ attribute :name, :string
+ attribute :payload, default: -> { {} }
+ attribute :metadata, default: -> { {} }
+ attribute :created_at, :datetime
# @param name [String] The event name (e.g., 'order.complete')
# @param payload [Hash] The serialized event data
# @param metadata [Hash] Additional contextual information
- def initialize(name:, payload:, metadata: {})
- @name = name.to_s.freeze
- @payload = (payload || {}).deep_stringify_keys.freeze
- @timestamp = Time.current.freeze
- @metadata = build_metadata(metadata).freeze
+ def initialize(name: nil, payload: {}, metadata: {})
+ super()
+ @created_at = Time.current.freeze
+ self.id = SecureRandom.uuid
+ self.name = name.to_s.freeze if name
+ self.payload = (payload || {}).deep_stringify_keys.freeze
+ self.metadata = build_metadata(metadata).freeze
+ self.created_at = @created_at
end
# Returns the resource type from the event name
# @return [String] The resource type (e.g., 'order' from 'order.complete')
def resource_type
- @resource_type ||= name.split('.').first
+ @resource_type ||= name.to_s.split('.').first
end
# Returns the action from the event name
# @return [String] The action (e.g., 'complete' from 'order.complete')
def action
- @action ||= name.split('.').drop(1).join('.')
+ @action ||= name.to_s.split('.').drop(1).join('.')
end
# Checks if the event matches a pattern
@@ -68,27 +81,29 @@ module Spree
end
end
- # Convert to hash representation
- # @return [Hash]
- def to_h
+ def attributes
{
- name: name,
- payload: payload,
- metadata: metadata,
- timestamp: timestamp
+ 'id' => id,
+ 'name' => name,
+ 'payload' => payload,
+ 'metadata' => metadata,
+ 'created_at' => created_at
}
end
+ def to_h
+ attributes.symbolize_keys
+ end
+
def inspect
- "#<Spree::Event name=#{name.inspect} timestamp=#{timestamp.iso8601}>"
+ "#<Spree::Event id=#{id.inspect} name=#{name.inspect} created_at=#{created_at&.iso8601}>"
end
private
def build_metadata(custom_metadata)
base_metadata = {
- 'event_id' => SecureRandom.uuid,
- 'timestamp' => @timestamp.iso8601,
+ 'created_at' => @created_at.iso8601,
'spree_version' => Spree.version
}
@@ -104,8 +119,7 @@ module Spree
end
# Merge custom metadata and ensure IDs are strings for JSON consistency
- merged = base_metadata.merge(stringify_metadata(custom_metadata))
- merged
+ base_metadata.merge(stringify_metadata(custom_metadata || {}))
end
def stringify_metadata(hash)
diff --git a/core/lib/generators/spree/install/install_generator.rb b/core/lib/generators/spree/install/install_generator.rb
index da2d67871c..9f97a7e85f 100644
--- a/core/lib/generators/spree/install/install_generator.rb
+++ b/core/lib/generators/spree/install/install_generator.rb
@@ -110,7 +110,7 @@ module Spree
silence_warnings { rake 'active_storage:install:migrations' }
silence_warnings { rake 'action_text:install:migrations' }
silence_warnings { rake 'spree:install:migrations' }
- silence_warnings { rake 'spree_api:install:migrations' }
+ silence_warnings { rake 'spree_api:install:migrations' } if defined?(Spree::Api)
silence_warnings { rake 'spree_page_builder:install:migrations' } if @install_storefront
end
end
diff --git a/core/spec/lib/spree/events_spec.rb b/core/spec/lib/spree/events_spec.rb
index c2b86489e7..2297f845bc 100644
--- a/core/spec/lib/spree/events_spec.rb
+++ b/core/spec/lib/spree/events_spec.rb
@@ -20,12 +20,6 @@ RSpec.describe Spree::Events do
expect(event.payload).to eq({ 'id' => 1 })
end
- it 'includes metadata with IDs as strings' do
- event = described_class.publish('order.completed', { id: 1 }, { user_id: 5 })
-
- expect(event.metadata['user_id']).to eq('5')
- end
-
it 'notifies subscribers synchronously when async: false' do
received_events = []
diff --git a/core/spec/models/concerns/spree/publishable_spec.rb b/core/spec/models/concerns/spree/publishable_spec.rb
index be52e97229..a0da8813c6 100644
--- a/core/spec/models/concerns/spree/publishable_spec.rb
+++ b/core/spec/models/concerns/spree/publishable_spec.rb
@@ -65,16 +65,6 @@ RSpec.describe Spree::Publishable do
expect(received_event.payload).to eq({ 'custom' => 'data' })
end
- it 'includes model metadata with IDs as strings' do
- received_event = nil
- Spree::Events.subscribe('test_product.custom', async: false) { |e| received_event = e }
- Spree::Events.activate!
-
- instance.publish_event('test_product.custom')
-
- expect(received_event.metadata['model_id']).to eq('1')
- end
-
it 'does not publish when events are disabled' do
received = false
Spree::Events.subscribe('test_product.custom', async: false) { received = true }
diff --git a/docs/developer/customization/event-subscribers.mdx b/docs/developer/customization/event-subscribers.mdx
index a082a28ba1..bffb4f95b3 100644
--- a/docs/developer/customization/event-subscribers.mdx
+++ b/docs/developer/customization/event-subscribers.mdx
@@ -99,7 +99,7 @@ module MyApp
resource_type: 'Spree::Order',
resource_id: event.payload['id'],
action: action,
- occurred_at: event.timestamp
+ occurred_at: event.created_at
)
end
end
@@ -114,10 +114,11 @@ When your subscriber receives an event, you get a `Spree::Event` object with:
```ruby
def handle(event)
- event.name # => "order.complete"
- event.payload # => { "id" => 1, "number" => "R123456", ... }
- event.metadata # => { "model_class" => "Spree::Order", "model_id" => 1 }
- event.timestamp # => Time when event was published
+ event.id # => "550e8400-e29b-41d4-a716-446655440000" (UUID)
+ event.name # => "order.complete"
+ event.payload # => { "id" => 1, "number" => "R123456", ... }
+ event.metadata # => { "spree_version" => "5.1.0", "store_id" => "1" }
+ event.created_at # => Time when event was published
end
```
@@ -127,8 +128,8 @@ The payload contains serialized attributes, not the actual record. To get the re
```ruby
def handle(event)
- model_class = event.metadata['model_class'].constantize
- record = model_class.find_by(id: event.metadata['model_id'])
+ record_id = event.payload['id']
+ record = Spree::Order.find_by(id: record_id)
return unless record
# Work with the record
@@ -289,9 +290,8 @@ RSpec.describe MyApp::OrderCompletedSubscriber do
let(:order) { create(:completed_order_with_totals) }
let(:event) do
Spree::Event.new(
- 'order.complete',
- order.serializable_hash,
- { model_class: 'Spree::Order', model_id: order.id }
+ name: 'order.complete',
+ payload: Spree::Events::OrderSerializer.serialize(order)
)
end
@@ -362,7 +362,7 @@ module MyApp
private
def find_stock_item(event)
- Spree::StockItem.find_by(id: event.metadata['model_id'])
+ Spree::StockItem.find_by(id: event.payload['id'])
end
def stock_dropped_below_threshold?(event, stock_item)