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 subscriber generator and added a dedicated

Damian Legawieceb6a80d9d429
diff --git a/docs/developer/cli/quickstart.mdx b/docs/developer/cli/quickstart.mdx
index a906429419..dfbffaa841 100644
--- a/docs/developer/cli/quickstart.mdx
+++ b/docs/developer/cli/quickstart.mdx
@@ -185,6 +185,7 @@ Run a generator inside the container. Bare generator names are auto-prefixed wit
```bash
spree generate model Brand name:string slug:string:uniq # runs spree:model
spree generate api_resource Brand name:string slug:string:uniq # runs spree:api_resource — model + v3 Store/Admin API
+spree generate subscriber OmsOrderSync order.completed # runs spree:subscriber — event subscriber + registration
spree generate migration AddPositionToSpreeBrands position:integer # Rails built-in, forwarded as-is
```
diff --git a/docs/developer/core-concepts/events.mdx b/docs/developer/core-concepts/events.mdx
index 300c6629c1..3f9cec3d09 100644
--- a/docs/developer/core-concepts/events.mdx
+++ b/docs/developer/core-concepts/events.mdx
@@ -57,30 +57,42 @@ flowchart TB
## Creating a Subscriber
-Create a subscriber class in `app/subscribers/` that inherits from `Spree::Subscriber`:
+The fastest path is the generator — it creates the class, a spec stub, and registers the subscriber in `config/initializers/spree.rb` (the step that's easy to forget):
-```ruby app/subscribers/my_app/order_completed_subscriber.rb
-module MyApp
- class OrderCompletedSubscriber < Spree::Subscriber
- subscribes_to 'order.completed'
+<CodeGroup>
- def handle(event)
- order_id = event.payload['id']
- order = Spree::Order.find_by_prefix_id(order_id)
- return unless order
+```bash Spree CLI (Docker)
+spree generate subscriber OrderCompleted order.completed
+```
- # Your custom logic here
- ExternalService.notify_order_placed(order)
- end
+```bash Without Spree CLI
+bin/rails g spree:subscriber OrderCompleted order.completed
+```
+
+</CodeGroup>
+
+Or create the class by hand in `app/subscribers/`, inheriting from `Spree::Subscriber`:
+
+```ruby app/subscribers/order_completed_subscriber.rb
+class OrderCompletedSubscriber < Spree::Subscriber
+ subscribes_to 'order.completed'
+
+ def handle(event)
+ order_id = event.payload['id']
+ order = Spree::Order.find_by_prefix_id(order_id)
+ return unless order
+
+ # Your custom logic here
+ ExternalService.notify_order_placed(order)
end
end
```
Then register it in an initializer — subscribers are not auto-discovered (see [Registering Subscribers](#registering-subscribers)):
-```ruby config/initializers/event_subscribers.rb
+```ruby config/initializers/spree.rb
Rails.application.config.after_initialize do
- Spree.subscribers << MyApp::OrderCompletedSubscriber
+ Spree.subscribers << OrderCompletedSubscriber
end
```
@@ -109,37 +121,35 @@ end
When subscribing to multiple events, use the `on` DSL to route events to specific methods:
-```ruby app/subscribers/my_app/order_audit_subscriber.rb
-module MyApp
- class OrderAuditSubscriber < Spree::Subscriber
- subscribes_to 'order.completed', 'order.canceled', 'order.resumed'
+```ruby app/subscribers/order_audit_subscriber.rb
+class OrderAuditSubscriber < Spree::Subscriber
+ subscribes_to 'order.completed', 'order.canceled', 'order.resumed'
- on 'order.completed', :log_order_completed
- on 'order.canceled', :log_order_canceled
- on 'order.resumed', :log_order_resumed
+ on 'order.completed', :log_order_completed
+ on 'order.canceled', :log_order_canceled
+ on 'order.resumed', :log_order_resumed
- private
+ private
- def log_order_completed(event)
- create_audit_log(event, 'completed')
- end
+ def log_order_completed(event)
+ create_audit_log(event, 'completed')
+ end
- def log_order_canceled(event)
- create_audit_log(event, 'canceled')
- end
+ def log_order_canceled(event)
+ create_audit_log(event, 'canceled')
+ end
- def log_order_resumed(event)
- create_audit_log(event, 'resumed')
- end
+ def log_order_resumed(event)
+ create_audit_log(event, 'resumed')
+ end
- def create_audit_log(event, action)
- AuditLog.create!(
- resource_type: 'Spree::Order',
- resource_id: event.payload['id'],
- action: action,
- occurred_at: event.created_at
- )
- end
+ def create_audit_log(event, action)
+ AuditLog.create!(
+ resource_type: 'Spree::Order',
+ resource_id: event.payload['id'],
+ action: action,
+ occurred_at: event.created_at
+ )
end
end
```
@@ -368,8 +378,8 @@ When overriding serializers, make sure to include all attributes that webhooks a
If you add a custom model that publishes events, create a V3 serializer:
-```ruby app/models/my_app/subscription.rb
-module MyApp
+```ruby app/models/spree/subscription.rb
+module Spree
class Subscription < Spree.base_class
publishes_lifecycle_events
@@ -408,17 +418,17 @@ Models without a matching serializer will use a minimal fallback payload contain
## Registering Subscribers
-Subscribers are not auto-discovered — every subscriber must be registered explicitly, regardless of where the class lives. Add it to the `Spree.subscribers` array in an initializer:
+Subscribers are not auto-discovered — every subscriber must be registered explicitly, regardless of where the class lives. Add it to the `Spree.subscribers` array in `config/initializers/spree.rb` (or any initializer):
-```ruby config/initializers/event_subscribers.rb
+```ruby config/initializers/spree.rb
Rails.application.config.after_initialize do
- Spree.subscribers << MyApp::CustomSubscriber
+ Spree.subscribers << CustomSubscriber
end
```
To remove a built-in subscriber:
-```ruby config/initializers/event_subscribers.rb
+```ruby config/initializers/spree.rb
Rails.application.config.after_initialize do
Spree.subscribers.delete(Spree::ExportSubscriber)
end
@@ -464,10 +474,10 @@ This is useful for:
### Testing Event Handling
-```ruby spec/subscribers/my_app/order_completed_subscriber_spec.rb
+```ruby spec/subscribers/order_completed_subscriber_spec.rb
require 'spec_helper'
-RSpec.describe MyApp::OrderCompletedSubscriber do
+RSpec.describe OrderCompletedSubscriber do
let(:order) { create(:completed_order_with_totals) }
let(:event) do
Spree::Event.new(
@@ -524,41 +534,39 @@ end
Here's a complete example of a subscriber that sends alerts when inventory is low:
-```ruby app/subscribers/my_app/inventory_alert_subscriber.rb
-module MyApp
- class InventoryAlertSubscriber < Spree::Subscriber
- subscribes_to 'stock_item.updated'
+```ruby app/subscribers/inventory_alert_subscriber.rb
+class InventoryAlertSubscriber < Spree::Subscriber
+ subscribes_to 'stock_item.updated'
- LOW_STOCK_THRESHOLD = 10
+ LOW_STOCK_THRESHOLD = 10
- def handle(event)
- stock_item = find_stock_item(event)
- return unless stock_item
- return unless stock_dropped_below_threshold?(event, stock_item)
+ def handle(event)
+ stock_item = find_stock_item(event)
+ return unless stock_item
+ return unless stock_dropped_below_threshold?(event, stock_item)
- send_low_stock_alert(stock_item)
- end
+ send_low_stock_alert(stock_item)
+ end
- private
+ private
- def find_stock_item(event)
- Spree::StockItem.find_by_prefix_id(event.payload['id'])
- end
+ def find_stock_item(event)
+ Spree::StockItem.find_by_prefix_id(event.payload['id'])
+ end
- def stock_dropped_below_threshold?(event, stock_item)
- previous_count = event.payload['count_on_hand_before_last_save']
- current_count = stock_item.count_on_hand
+ def stock_dropped_below_threshold?(event, stock_item)
+ previous_count = event.payload['count_on_hand_before_last_save']
+ current_count = stock_item.count_on_hand
- previous_count >= LOW_STOCK_THRESHOLD && current_count < LOW_STOCK_THRESHOLD
- end
+ previous_count >= LOW_STOCK_THRESHOLD && current_count < LOW_STOCK_THRESHOLD
+ end
- def send_low_stock_alert(stock_item)
- InventoryMailer.low_stock_alert(
- variant: stock_item.variant,
- stock_location: stock_item.stock_location,
- count_on_hand: stock_item.count_on_hand
- ).deliver_later
- end
+ def send_low_stock_alert(stock_item)
+ InventoryMailer.low_stock_alert(
+ variant: stock_item.variant,
+ stock_location: stock_item.stock_location,
+ count_on_hand: stock_item.count_on_hand
+ ).deliver_later
end
end
```
diff --git a/docs/developer/customization/checkout.mdx b/docs/developer/customization/checkout.mdx
index abce1e31d0..119026f7a4 100644
--- a/docs/developer/customization/checkout.mdx
+++ b/docs/developer/customization/checkout.mdx
@@ -102,19 +102,17 @@ There are two approaches for adding logic around checkout state transitions:
For actions that should happen **after** a checkout step completes (syncing with external services, sending notifications, logging, etc.), use [Events subscribers](/developer/core-concepts/events). This is the recommended approach because it keeps your code decoupled from Spree internals.
-```ruby app/subscribers/my_app/order_completed_subscriber.rb
-module MyApp
- class OrderCompletedSubscriber < Spree::Subscriber
- subscribes_to 'order.completed'
-
- def handle(event)
- order = Spree::Order.find_by_prefix_id(event.payload['id'])
- return unless order
-
- # Sync to fulfillment system, notify warehouse, etc.
- FulfillmentService.notify(order)
- AnalyticsService.track_purchase(order)
- end
+```ruby app/subscribers/order_completed_subscriber.rb
+class OrderCompletedSubscriber < Spree::Subscriber
+ subscribes_to 'order.completed'
+
+ def handle(event)
+ order = Spree::Order.find_by_prefix_id(event.payload['id'])
+ return unless order
+
+ # Sync to fulfillment system, notify warehouse, etc.
+ FulfillmentService.notify(order)
+ AnalyticsService.track_purchase(order)
end
end
```
diff --git a/docs/developer/customization/decorators.mdx b/docs/developer/customization/decorators.mdx
index d942bd9625..f13cea2bc4 100644
--- a/docs/developer/customization/decorators.mdx
+++ b/docs/developer/customization/decorators.mdx
@@ -503,19 +503,17 @@ end
**After (Events subscriber):**
-```ruby app/subscribers/my_app/product_sync_subscriber.rb
-module MyApp
- class ProductSyncSubscriber < Spree::Subscriber
- subscribes_to 'product.updated'
-
- def handle(event)
- product = Spree::Product.find_by_prefix_id(event.payload['id'])
- return unless product
-
- # The payload includes changes, check if name changed
- if event.payload['previous_changes']&.key?('name')
- ExternalSyncJob.perform_later(product)
- end
+```ruby app/subscribers/product_sync_subscriber.rb
+class ProductSyncSubscriber < Spree::Subscriber
+ subscribes_to 'product.updated'
+
+ def handle(event)
+ product = Spree::Product.find_by_prefix_id(event.payload['id'])
+ return unless product
+
+ # The payload includes changes, check if name changed
+ if event.payload['previous_changes']&.key?('name')
+ ExternalSyncJob.perform_later(product)
end
end
end
diff --git a/docs/developer/customization/quickstart.mdx b/docs/developer/customization/quickstart.mdx
index 9891877682..d23da7806a 100644
--- a/docs/developer/customization/quickstart.mdx
+++ b/docs/developer/customization/quickstart.mdx
@@ -55,18 +55,16 @@ Spree is a flexible platform allowing you to customize every part of it to suit
Spree's event system lets you subscribe to events like `order.completed`, `product.updated`, `payment.paid`, etc.:
- ```ruby app/subscribers/my_app/order_completed_subscriber.rb
- module MyApp
- class OrderCompletedSubscriber < Spree::Subscriber
- subscribes_to 'order.completed'
+ ```ruby app/subscribers/order_completed_subscriber.rb
+ class OrderCompletedSubscriber < Spree::Subscriber
+ subscribes_to 'order.completed'
- def handle(event)
- order = Spree::Order.find_by_prefix_id(event.payload['id'])
- return unless order
+ def handle(event)
+ order = Spree::Order.find_by_prefix_id(event.payload['id'])
+ return unless order
- # Sync to external service, send notification, etc.
- ExternalService.notify_order_placed(order)
- end
+ # Sync to external service, send notification, etc.
+ ExternalService.notify_order_placed(order)
end
end
```
diff --git a/docs/developer/tutorial/admin.mdx b/docs/developer/tutorial/admin.mdx
index 9bf76d4ceb..cdcbbb035c 100644
--- a/docs/developer/tutorial/admin.mdx
+++ b/docs/developer/tutorial/admin.mdx
@@ -15,7 +15,7 @@ The Admin Scaffold generator creates a complete admin section for a resource:
spree generate spree:admin:scaffold Spree::Brand
```
-```bash Rails (native)
+```bash Without Spree CLI
bin/rails g spree:admin:scaffold Spree::Brand
```
diff --git a/docs/developer/tutorial/api.mdx b/docs/developer/tutorial/api.mdx
index e99bad9acf..1069c201fe 100644
--- a/docs/developer/tutorial/api.mdx
+++ b/docs/developer/tutorial/api.mdx
@@ -28,7 +28,7 @@ Everything this page builds by hand can be generated in one command with `spree:
spree generate api_resource Brand
```
-```bash Rails (native)
+```bash Without Spree CLI
bin/rails g spree:api_resource Brand
```
@@ -79,7 +79,7 @@ spree generate migration AddSlugToSpreeBrands slug:string:uniq
spree migrate
```
-```bash Rails (native)
+```bash Without Spree CLI
bin/rails g migration AddSlugToSpreeBrands slug:string:uniq
bin/rails db:migrate
```
@@ -613,6 +613,7 @@ Spree.ransack.add_association(Spree::Product, :brand)
## Related Documentation
- [Extending Core Models](/developer/tutorial/extending-models) - Adding the Brand association to Product
+- [Events & Webhooks](/developer/tutorial/events) - Lifecycle events for Brand and external-system integration (next step)
- [Using Brands with the SDK](/developer/tutorial/sdk) - Consuming brand endpoints from TypeScript
- [Decorators](/developer/customization/decorators) - Full decorator reference
- [Dependencies](/developer/customization/dependencies) - Swapping services and serializers
diff --git a/docs/developer/tutorial/events.mdx b/docs/developer/tutorial/events.mdx
new file mode 100644
index 0000000000..24f7275a36
--- /dev/null
+++ b/docs/developer/tutorial/events.mdx
@@ -0,0 +1,172 @@
+---
+title: Events & Webhooks
+description: React to store activity and connect Spree to external systems — an OMS, a warehouse, an ERP — with subscribers and webhooks
+---
+
+<Info>
+ This guide assumes you've completed the [Model](/developer/tutorial/model) and [API](/developer/tutorial/api) tutorials — we'll reuse the Brand serializer created there.
+</Info>
+
+Almost every real store talks to other systems: an order management system (OMS), a warehouse (WMS), an ERP, a CRM, a marketing platform. In Spree, the integration surface is the **events system** — models publish events as things happen, and you react to them without touching core code.
+
+There are two ways to consume events, and they serve different audiences:
+
+| Mechanism | Code lives | Best for |
+|---|---|---|
+| **Subscriber** | In your Spree app | Calling external APIs with your own client code, internal side effects, anything needing app context |
+| **Webhook** | In the external system | Letting a third party receive HTTP callbacks — no Ruby in your app, endpoints managed from the admin |
+
+We'll do both: push completed orders to an OMS with a subscriber, give the Brand model its own lifecycle events, and set up an outbound webhook.
+
+## Step 1: Subscribe to a Core Event
+
+When an order completes, send it to the OMS. Generate a subscriber:
+
+<CodeGroup>
+
+```bash Spree CLI (Docker)
+spree generate subscriber OmsOrderSync order.completed
+```
+
+```bash Without Spree CLI
+bin/rails g spree:subscriber OmsOrderSync order.completed
+```
+
+</CodeGroup>
+
+This creates the subscriber, a spec stub, and — crucially — **registers it** in `config/initializers/spree.rb` (injected into the existing `after_initialize` block every Spree app ships with). Subscribers are not auto-discovered; a subscriber that never gets appended to `Spree.subscribers` is a silent no-op, which is why the generator owns that step (re-runs are idempotent, and each new subscriber appends to the same initializer).
+
+Fill in the handler:
+
+```ruby app/subscribers/oms_order_sync_subscriber.rb
+class OmsOrderSyncSubscriber < Spree::Subscriber
+ subscribes_to 'order.completed'
+
+ def handle(event)
+ order = Spree::Order.find_by_prefix_id(event.payload['id'])
+ return unless order
+
+ OmsClient.create_order(
+ number: order.number,
+ email: order.email,
+ line_items: order.line_items.map { |li| { sku: li.sku, quantity: li.quantity } }
+ )
+ end
+end
+```
+
+Two things worth understanding:
+
+- **Payloads carry prefixed IDs**, not raw database IDs — always look records up with `find_by_prefix_id`. The payload itself is the resource serialized with its v3 API serializer, so `event.payload['number']`, `['email']`, etc. are available directly when you don't need the full record.
+- **Subscribers run async by default** — each `handle` call is an ActiveJob on the events queue, so a slow OMS API never blocks checkout. Pass `subscribes_to 'order.completed', async: false` only when you genuinely need synchronous execution.
+
+Restart the server, complete a test order, and watch the job fire (`spree logs worker` — or your job backend's UI).
+
+## Step 2: Give Brand Its Own Lifecycle Events
+
+Core models like Payment and Shipment publish `*.created` / `*.updated` / `*.deleted` events automatically. Your models can too — add one line to the Brand model:
+
+```ruby app/models/spree/brand.rb {3}
+module Spree
+ class Brand < Spree.base_class
+ publishes_lifecycle_events
+
+ # ... existing code ...
+ end
+end
+```
+
+Now `brand.created`, `brand.updated`, and `brand.deleted` fire after the matching transactions commit — and because you created `Spree::Api::V3::BrandSerializer` in the [API step](/developer/tutorial/api), the payloads automatically use it (the events system resolves the serializer by naming convention). Anyone — subscriber or webhook — can react to brand changes with the same JSON shape your API serves.
+
+<CodeGroup>
+
+```bash Spree CLI (Docker)
+spree generate subscriber BrandSync brand.created brand.updated
+```
+
+```bash Without Spree CLI
+bin/rails g spree:subscriber BrandSync brand.created brand.updated
+```
+
+</CodeGroup>
+
+```ruby app/subscribers/brand_sync_subscriber.rb
+class BrandSyncSubscriber < Spree::Subscriber
+ subscribes_to 'brand.created', 'brand.updated'
+
+ def handle(event)
+ SearchIndexer.upsert_brand(event.payload)
+ end
+end
+```
+
+## Step 3: Publish a Custom Event
+
+Lifecycle events cover persistence; custom events express *domain* moments. Say featuring a brand should notify the marketing platform:
+
+```ruby
+brand.publish_event('brand.featured')
+```
+
+The payload defaults to the serializer output; pass your own hash as the second argument when the event needs different data. Subscribers consume it like any other event name.
+
+## Step 4: Outbound Webhooks — No Code Required
+
+When the consumer is an external system you don't deploy code into, use webhooks. In the admin, go to **Settings → Webhooks**, add an endpoint with the destination URL, and pick the events to deliver — `order.completed`, `brand.created`, anything publishing in your store. The endpoint's **signing secret is shown once on creation** — store it in the receiving system.
+
+Each delivery is an HTTP POST with this envelope:
+
+```json
+{
+ "id": "550e8400-e29b-41d4-a716-446655440000",
+ "name": "order.completed",
+ "created_at": "2026-06-11T12:00:00Z",
+ "data": { "id": "or_m3Rp9wXz", "number": "R123456789", "...": "..." },
+ "metadata": {}
+}
+```
+
+And three headers the receiver should use:
+
+| Header | Contents |
+|---|---|
+| `X-Spree-Webhook-Event` | The event name |
+| `X-Spree-Webhook-Timestamp` | Unix timestamp of the delivery |
+| `X-Spree-Webhook-Signature` | `HMAC-SHA256(secret, "{timestamp}.{body}")` |
+
+Verify the signature before trusting a payload:
+
+```ruby
+def verified?(request, secret)
+ timestamp = request.headers['X-Spree-Webhook-Timestamp']
+ expected = OpenSSL::HMAC.hexdigest('SHA256', secret, "#{timestamp}.#{request.raw_post}")
+ ActiveSupport::SecurityUtils.secure_compare(expected, request.headers['X-Spree-Webhook-Signature'])
+end
+```
+
+Delivery semantics to design around: failed deliveries (timeouts, connection errors, non-2xx responses) are **recorded, not retried automatically** — redeliver from the endpoint's delivery history in the admin, or via `POST /api/v3/admin/webhook_endpoints/:webhook_endpoint_id/deliveries/:id/redeliver`. After **15 consecutive failures** the endpoint auto-disables and store staff get an email; a successful delivery resets the counter.
+
+## Testing a Subscriber
+
+Subscribers are plain Ruby — test `handle` directly with a constructed event:
+
+```ruby spec/subscribers/oms_order_sync_subscriber_spec.rb
+require 'rails_helper'
+
+RSpec.describe OmsOrderSyncSubscriber do
+ it 'pushes completed orders to the OMS' do
+ order = create(:completed_order_with_totals)
+ event = Spree::Event.new(name: 'order.completed', payload: { 'id' => order.prefixed_id })
+
+ expect(OmsClient).to receive(:create_order).with(hash_including(number: order.number))
+
+ described_class.new.handle(event)
+ end
+end
+```
+
+## Related Documentation
+
+- [Events](/developer/core-concepts/events) — the full event catalog, subscriber DSL, and delivery guarantees
+- [Webhooks](/developer/core-concepts/webhooks) — endpoint management, security, and the per-event payload schemas
+- [Extending Core Models](/developer/tutorial/extending-models) — when a decorator is the right tool instead
diff --git a/docs/developer/tutorial/extending-models.mdx b/docs/developer/tutorial/extending-models.mdx
index bc1a534ea9..81580690b7 100644
--- a/docs/developer/tutorial/extending-models.mdx
+++ b/docs/developer/tutorial/extending-models.mdx
@@ -87,7 +87,7 @@ First, add a `brand_id` column to the products table:
spree generate migration AddBrandIdToSpreeProducts brand_id:integer:index
```
-```bash Rails (native)
+```bash Without Spree CLI
bin/rails g migration AddBrandIdToSpreeProducts brand_id:integer:index
```
@@ -112,7 +112,7 @@ Run the migration:
spree migrate
```
-```bash Rails (native)
+```bash Without Spree CLI
bin/rails db:migrate
```
@@ -132,7 +132,7 @@ Spree provides a generator to create decorator files with the correct structure:
spree generate model_decorator Spree::Product
```
-```bash Rails (native)
+```bash Without Spree CLI
bin/rails g spree:model_decorator Spree::Product
```
@@ -323,22 +323,7 @@ def normalize_name
end
```
-**Events approach** (recommended for side effects):
-
-```ruby app/subscribers/my_app/product_sync_subscriber.rb
-module MyApp
- class ProductSyncSubscriber < Spree::Subscriber
- subscribes_to 'product.updated'
-
- def handle(event)
- product = Spree::Product.find_by_prefix_id(event.payload['id'])
- return unless product
-
- ExternalSyncService.sync(product)
- end
- end
-end
-```
+**Events approach** (recommended for side effects): subscribe to `product.updated` and react in a `Spree::Subscriber` — no decorator, no callback coupling. The [Events & Webhooks tutorial](/developer/tutorial/events) builds this out fully, including external-system sync (OMS, warehouse) and outbound webhooks.
#### Adding Class Methods
@@ -426,6 +411,7 @@ Now that Brands are connected to Products, let's expose them through the Store A
- [Model Tutorial](/developer/tutorial/model) - Creating the Brand model
- [Admin Tutorial](/developer/tutorial/admin) - Building the admin interface
- [API Tutorial](/developer/tutorial/api) - Exposing brands through the API
+- [Events & Webhooks tutorial](/developer/tutorial/events) - Subscribers, custom events, and webhooks in the Brand storyline
- [Events](/developer/core-concepts/events) - Subscribe to model changes without decorators
- [Webhooks](/developer/core-concepts/webhooks) - HTTP callbacks for external integrations
- [Decorators](/developer/customization/decorators) - Full decorator reference
diff --git a/docs/developer/tutorial/introduction.mdx b/docs/developer/tutorial/introduction.mdx
index 10df0b5af0..b7586a0893 100644
--- a/docs/developer/tutorial/introduction.mdx
+++ b/docs/developer/tutorial/introduction.mdx
@@ -16,7 +16,7 @@ You need a running Spree app. The fastest path is [create-spree-app](/developer/
npx create-spree-app@latest my-store
```
-A classic Rails app with Spree gems works just as well. **Every command in this tutorial is shown in two forms** — `spree <command>` (Spree CLI, runs inside Docker) and `bin/rails …` (native) — pick the column that matches your setup and ignore the other.
+An existing app with Spree gems works just as well. **Every command in this tutorial is shown in two forms** — **Spree CLI** (runs inside Docker) and **Without Spree CLI** (runs directly on your machine) — pick the tab that matches your setup and ignore the other.
<Note>
**create-spree-app projects:** run `spree eject` once before starting. Fresh projects use a prebuilt Docker image; ejecting switches to the dev setup that mounts `backend/` into the container, so the files the generators create land in your project (and reload live as you edit them).
@@ -33,6 +33,7 @@ A classic Rails app with Spree gems works just as well. **Every command in this
* A `brand` association on Products, surfaced in the product admin form
* Store API endpoints (`GET /api/v3/store/brands`) with serializers and prefixed IDs
* Typed TypeScript access to brands from your storefront via `@spree/sdk`
+* Event subscribers and webhooks connecting the store to external systems
* Automated tests for all of it
## Tutorial Sections
@@ -50,10 +51,13 @@ A classic Rails app with Spree gems works just as well. **Every command in this
<Card title="4. API" icon="code" href="/developer/tutorial/api">
Expose Brands through the Store and Admin APIs — generated in one command, or hand-built to learn the pieces
</Card>
- <Card title="5. SDK" icon="js" href="/developer/tutorial/sdk">
+ <Card title="5. Events & Webhooks" icon="zap" href="/developer/tutorial/events">
+ React to store activity and connect external systems — OMS, warehouse, ERP
+ </Card>
+ <Card title="6. SDK" icon="js" href="/developer/tutorial/sdk">
Consume Brand endpoints from TypeScript using the SDK
</Card>
- <Card title="6. Testing" icon="flask-vial" href="/developer/tutorial/testing">
+ <Card title="7. Testing" icon="flask-vial" href="/developer/tutorial/testing">
Write automated tests for your feature
</Card>
</CardGroup>
diff --git a/docs/developer/tutorial/model.mdx b/docs/developer/tutorial/model.mdx
index 1d6b526742..3c052ff687 100644
--- a/docs/developer/tutorial/model.mdx
+++ b/docs/developer/tutorial/model.mdx
@@ -15,14 +15,14 @@ Spree ships a `spree:model` generator that produces a model and migration follow
spree generate model Brand name:string:index description:rich_text logo:attachment
```
-```bash Rails (native)
+```bash Without Spree CLI
bin/rails g spree:model Brand name:string:index description:rich_text logo:attachment
```
</CodeGroup>
<Info>
- Throughout this tutorial every command is shown in two forms. **Spree CLI** is for projects created with [create-spree-app](/developer/create-spree-app/quickstart), where the app runs in Docker and `spree <command>` routes into the container. **Rails (native)** is for classic Rails apps running Spree directly on your machine.
+ Throughout this tutorial every command is shown in two forms. **Spree CLI** is for projects created with [create-spree-app](/developer/create-spree-app/quickstart), where the app runs in Docker and `spree <command>` routes into the container. **Without Spree CLI** is for apps running Spree backend directly on your machine.
</Info>
This creates two files:
@@ -38,7 +38,7 @@ Now apply the migration:
spree migrate
```
-```bash Rails (native)
+```bash Without Spree CLI
bin/rails db:migrate
```
@@ -84,7 +84,7 @@ Line by line:
spree console
```
-```bash Rails (native)
+```bash Without Spree CLI
bin/rails console
```
diff --git a/docs/developer/tutorial/testing.mdx b/docs/developer/tutorial/testing.mdx
index 11a239d672..1ff149fc6f 100644
--- a/docs/developer/tutorial/testing.mdx
+++ b/docs/developer/tutorial/testing.mdx
@@ -26,7 +26,7 @@ spree generate rspec:install
spree generate spree_dev_tools:install
```
-```bash Rails (native)
+```bash Without Spree CLI
bin/rails g rspec:install
bin/rails g spree_dev_tools:install
```
@@ -610,7 +610,7 @@ spree-rspec --format documentation # documentation format
spree-rspec spec/features/ # only feature tests
```
-```bash Rails (native)
+```bash Without Spree CLI
bundle exec rspec # all tests
bundle exec rspec spec/models/spree/brand_spec.rb # specific file
bundle exec rspec spec/models/spree/brand_spec.rb:15 # specific test
diff --git a/docs/docs.json b/docs/docs.json
index 0e4d166515..82bff6537b 100644
--- a/docs/docs.json
+++ b/docs/docs.json
@@ -290,6 +290,7 @@
"developer/tutorial/admin",
"developer/tutorial/extending-models",
"developer/tutorial/api",
+ "developer/tutorial/events",
"developer/tutorial/sdk",
"developer/tutorial/testing"
]
diff --git a/spree/core/lib/generators/spree/subscriber/subscriber_generator.rb b/spree/core/lib/generators/spree/subscriber/subscriber_generator.rb
new file mode 100644
index 0000000000..d65bf2e220
--- /dev/null
+++ b/spree/core/lib/generators/spree/subscriber/subscriber_generator.rb
@@ -0,0 +1,116 @@
+# frozen_string_literal: true
+
+module Spree
+ # spree:subscriber — scaffold an event subscriber and register it.
+ #
+ # bin/rails g spree:subscriber OmsOrderSync order.completed order.canceled
+ # bin/rails g spree:subscriber MyApp::BrandSync brand.created brand.updated
+ # bin/rails g spree:subscriber CriticalSync order.completed --sync
+ #
+ # Subscribers are not auto-discovered — they must be appended to the
+ # Spree.subscribers array. Forgetting that step produces a silent no-op,
+ # so this generator also maintains the registration in
+ # config/initializers/spree.rb with an idempotent line per subscriber.
+ class SubscriberGenerator < Rails::Generators::NamedBase
+ desc 'Creates a Spree event subscriber and registers it in an initializer'
+
+ # Every Spree app ships config/initializers/spree.rb (created by
+ # spree:install) — registrations go there rather than into a second
+ # initializer file.
+ INITIALIZER_PATH = 'config/initializers/spree.rb'
+ REGISTRATION_ANCHOR = "Rails.application.config.after_initialize do\n"
+
+ argument :events, type: :array, default: [], banner: 'event.name event.name'
+
+ class_option :sync,
+ type: :boolean,
+ default: false,
+ desc: 'Run the subscriber synchronously (async: false) instead of via ActiveJob'
+
+ class_option :skip_spec,
+ type: :boolean,
+ default: false,
+ desc: "Don't generate a spec file"
+
+ def self.source_paths
+ [File.expand_path('templates', __dir__), *superclass.source_paths]
+ end
+
+ def create_subscriber_file
+ template 'subscriber.rb.tt', File.join('app/subscribers', class_path, "#{subscriber_file_name}.rb")
+ end
+
+ def register_subscriber
+ if File.exist?(destination_path(INITIALIZER_PATH))
+ content = File.read(destination_path(INITIALIZER_PATH))
+ if content.include?(registration_line.strip)
+ say_status :identical, "#{INITIALIZER_PATH} (#{subscriber_class_name} already registered)", :blue
+ elsif content.include?(REGISTRATION_ANCHOR)
+ inject_into_file INITIALIZER_PATH, registration_line, after: REGISTRATION_ANCHOR
+ else
+ append_to_file INITIALIZER_PATH, registration_block
+ end
+ else
+ create_file INITIALIZER_PATH, registration_block.lstrip
+ end
+ end
+
+ def create_spec_file
+ return if options[:skip_spec]
+
+ template 'subscriber_spec.rb.tt', File.join('spec/subscribers', class_path, "#{subscriber_file_name}_spec.rb")
+ end
+
+ def warn_about_missing_events
+ return if events.any?
+
+ say_status :note, "no events given — edit `subscribes_to` in the generated subscriber (e.g. 'order.completed')", :yellow
+ end
+
+ private
+
+ # "OmsOrderSync" and "OmsOrderSyncSubscriber" both produce
+ # OmsOrderSyncSubscriber / oms_order_sync_subscriber.
+ def bare_subscriber_name
+ base = class_name.demodulize.sub(/Subscriber\z/, '')
+ "#{base}Subscriber"
+ end
+
+ def subscriber_file_name
+ bare_subscriber_name.underscore
+ end
+
+ def subscriber_class_name
+ (class_path.map { |part| part.camelize } + [bare_subscriber_name]).join('::')
+ end
+
+ def namespace_modules
+ class_path.map(&:camelize)
+ end
+
+ def subscribes_to_arguments
+ listed = events.any? ? events.map { |e| "'#{e}'" } : ["'TODO.replace_with_event_name'"]
+ listed << 'async: false' if options[:sync]
+ listed.join(', ')
+ end
+
+ def registration_line
+ " Spree.subscribers << #{subscriber_class_name}\n"
+ end
+
+ def registration_block
+ <<~RUBY
+
+ # Event subscribers must be registered explicitly — Spree does not
+ # auto-discover classes in app/subscribers/.
+ Rails.application.config.after_initialize do
+ #{registration_line.chomp}
+ end
+ RUBY
+ end
+
+ def destination_path(relative)
+ File.join(destination_root, relative)
+ end
+ end
+end
diff --git a/spree/core/lib/generators/spree/subscriber/templates/subscriber.rb.tt b/spree/core/lib/generators/spree/subscriber/templates/subscriber.rb.tt
new file mode 100644
index 0000000000..823ccaecff
--- /dev/null
+++ b/spree/core/lib/generators/spree/subscriber/templates/subscriber.rb.tt
@@ -0,0 +1,17 @@
+<% namespace_modules.each_with_index do |mod, i| -%>
+<%= ' ' * i %>module <%= mod %>
+<% end -%>
+<% depth = namespace_modules.size -%>
+<%= ' ' * depth %>class <%= bare_subscriber_name %> < Spree::Subscriber
+<%= ' ' * (depth + 1) %>subscribes_to <%= subscribes_to_arguments %>
+
+<%= ' ' * (depth + 1) %>def handle(event)
+<%= ' ' * (depth + 2) %># Event payloads carry prefixed IDs — look records up with find_by_prefix_id:
+<%= ' ' * (depth + 2) %>#
+<%= ' ' * (depth + 2) %># record = Spree::Order.find_by_prefix_id(event.payload['id'])
+<%= ' ' * (depth + 2) %># return unless record
+<%= ' ' * (depth + 1) %>end
+<%= ' ' * depth %>end
+<% namespace_modules.each_with_index do |_, i| -%>
+<%= ' ' * (namespace_modules.size - 1 - i) %>end
+<% end -%>
diff --git a/spree/core/lib/generators/spree/subscriber/templates/subscriber_spec.rb.tt b/spree/core/lib/generators/spree/subscriber/templates/subscriber_spec.rb.tt
new file mode 100644
index 0000000000..1ac1371e01
--- /dev/null
+++ b/spree/core/lib/generators/spree/subscriber/templates/subscriber_spec.rb.tt
@@ -0,0 +1,9 @@
+require 'rails_helper'
+
+RSpec.describe <%= subscriber_class_name %> do
+ it 'handles <%= events.first || 'the subscribed event' %>' do
+ event = Spree::Event.new(name: <%= (events.first || 'some.event').inspect %>, payload: { 'id' => 'prefixed_id_here' })
+
+ expect { described_class.new.handle(event) }.not_to raise_error
+ end
+end
diff --git a/spree/core/spec/lib/generators/spree/subscriber/subscriber_generator_spec.rb b/spree/core/spec/lib/generators/spree/subscriber/subscriber_generator_spec.rb
new file mode 100644
index 0000000000..581112579b
--- /dev/null
+++ b/spree/core/spec/lib/generators/spree/subscriber/subscriber_generator_spec.rb
@@ -0,0 +1,126 @@
+require 'spec_helper'
+require 'fileutils'
+require 'rails/generators'
+require 'generators/spree/subscriber/subscriber_generator'
+
+RSpec.describe Spree::SubscriberGenerator, type: :generator do
+ let(:destination) { File.expand_path('../../../../../tmp/subscriber_generator_test', __dir__) }
+
+ before do
+ FileUtils.rm_rf(destination)
+ FileUtils.mkdir_p(destination)
+ end
+
+ after do
+ FileUtils.rm_rf(destination)
+ end
+
+ def run_generator(argv)
+ described_class.start(argv, destination_root: destination)
+ end
+
+ def read(relative)
+ path = File.join(destination, relative)
+ File.exist?(path) && File.read(path)
+ end
+
+ it 'generates a subscriber with the events and a handle method' do
+ run_generator(['OmsOrderSync', 'order.completed', 'order.canceled'])
+
+ subscriber = read('app/subscribers/oms_order_sync_subscriber.rb')
+ expect(subscriber).to include('class OmsOrderSyncSubscriber < Spree::Subscriber')
+ expect(subscriber).to include("subscribes_to 'order.completed', 'order.canceled'")
+ expect(subscriber).to include('def handle(event)')
+ end
+
+ it 'does not double the Subscriber suffix' do
+ run_generator(['OmsOrderSyncSubscriber', 'order.completed'])
+
+ expect(read('app/subscribers/oms_order_sync_subscriber.rb')).to include('class OmsOrderSyncSubscriber')
+ expect(read('app/subscribers/oms_order_sync_subscriber.rb')).not_to include('SubscriberSubscriber')
+ end
+
+ it 'creates config/initializers/spree.rb with the registration when absent' do
+ run_generator(['OmsOrderSync', 'order.completed'])
+
+ initializer = read('config/initializers/spree.rb')
+ expect(initializer).to include('Rails.application.config.after_initialize do')
+ expect(initializer).to include('Spree.subscribers << OmsOrderSyncSubscriber')
+ end
+
+ it 'injects into an existing after_initialize block in spree.rb' do
+ FileUtils.mkdir_p(File.join(destination, 'config/initializers'))
+ File.write(File.join(destination, 'config/initializers/spree.rb'), <<~RUBY)
+ Spree.config do |config|
+ config.track_inventory_levels = true
+ end
+
+ Rails.application.config.after_initialize do
+ Spree.dependencies.cart_add_item_service = 'MyApp::AddItem'
+ end
+ RUBY
+
+ run_generator(['OmsOrderSync', 'order.completed'])
+
+ initializer = read('config/initializers/spree.rb')
+ expect(initializer).to include("Rails.application.config.after_initialize do\n Spree.subscribers << OmsOrderSyncSubscriber")
+ expect(initializer).to include('track_inventory_levels')
+ expect(initializer.scan('after_initialize').size).to eq(1)
+ end
+
+ it 'appends a new after_initialize block when spree.rb has none' do
+ FileUtils.mkdir_p(File.join(destination, 'config/initializers'))
+ File.write(File.join(destination, 'config/initializers/spree.rb'), <<~RUBY)
+ Spree.config do |config|
+ config.track_inventory_levels = true
+ end
+ RUBY
+
+ run_generator(['OmsOrderSync', 'order.completed'])
+
+ initializer = read('config/initializers/spree.rb')
+ expect(initializer).to include('track_inventory_levels')
+ expect(initializer).to include('Rails.application.config.after_initialize do')
+ expect(initializer).to include('Spree.subscribers << OmsOrderSyncSubscriber')
+ end
+
+ it 'appends to an existing initializer without duplicating registrations' do
+ run_generator(['OmsOrderSync', 'order.completed'])
+ run_generator(['BrandSync', 'brand.created'])
+ run_generator(['OmsOrderSync', 'order.completed'])
+
+ initializer = read('config/initializers/spree.rb')
+ expect(initializer.scan('Spree.subscribers << OmsOrderSyncSubscriber').size).to eq(1)
+ expect(initializer).to include('Spree.subscribers << BrandSyncSubscriber')
+ end
+
+ it 'supports namespaced subscribers with nested modules' do
+ run_generator(['MyApp::BrandSync', 'brand.created'])
+
+ subscriber = read('app/subscribers/my_app/brand_sync_subscriber.rb')
+ expect(subscriber).to include("module MyApp\n class BrandSyncSubscriber < Spree::Subscriber")
+ expect(read('config/initializers/spree.rb')).to include('Spree.subscribers << MyApp::BrandSyncSubscriber')
+ end
+
+ it 'adds async: false with --sync' do
+ run_generator(['CriticalSync', 'order.completed', '--sync'])
+
+ expect(read('app/subscribers/critical_sync_subscriber.rb')).to include("subscribes_to 'order.completed', async: false")
+ end
+
+ it 'emits a TODO placeholder when no events are given' do
+ run_generator(['Mystery'])
+
+ expect(read('app/subscribers/mystery_subscriber.rb')).to include("subscribes_to 'TODO.replace_with_event_name'")
+ end
+
+ it 'generates a spec file unless --skip-spec' do
+ run_generator(['OmsOrderSync', 'order.completed'])
+ expect(read('spec/subscribers/oms_order_sync_subscriber_spec.rb')).to include('RSpec.describe OmsOrderSyncSubscriber')
+
+ FileUtils.rm_rf(destination)
+ FileUtils.mkdir_p(destination)
+ run_generator(['OmsOrderSync', 'order.completed', '--skip-spec'])
+ expect(read('spec/subscribers/oms_order_sync_subscriber_spec.rb')).to be(false)
+ end
+end