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.

9.7 KB
Raw Blame
---
title: Dependencies
section: customization
---

## Overview

With Dependencies, you can replace parts of Spree core with your custom code:
[Services and Workflows](/developer/customization/workflows), the staff ability class
and the storefront access policy (used for [Permissions](/developer/customization/permissions)), and API Serializers (used for
generating JSON API responses).

<Tip>
Replacing a whole class means keeping your copy in sync with every Spree
release. If you only need to run code inside an existing flow — validating,
reacting, or contributing data to a calculation — use a
[hook](/developer/customization/workflows#extending-a-workflow-with-hooks)
instead. Hooks survive upgrades.
</Tip>

## Application (global) customization

This will change every aspect of the application (the Store API, the Admin API, and everything built on them).

In your `config/initializers/spree.rb` file, you can set the following:

```ruby
Spree.carts_update_service = MyStore::CartUpdate
```

or using the block syntax:

```ruby
Spree.dependencies do |dependencies|
  dependencies.carts_update_service = MyStore::CartUpdate
end
```

Now let's create your custom service.

```bash
mkdir -p app/services/my_store && touch app/services/my_store/cart_update.rb
```

And add the following code to it:

```ruby
module MyStore
  class CartUpdate < Spree::Carts::Update
    def call(cart:, params:)
      result = super

      MyStore::ErpSync.push(result.value) if result.success?

      result
    end
  end
end
```

Inheriting and calling `super` keeps Spree's behaviour and adds yours around it,
which is usually what you want — a full rewrite means re-implementing logic that
changes between releases.

### Replacing a workflow

Workflow-backed seams end in `_workflow` (`cart_add_item_workflow`,
`carts_complete_workflow`, `payment_capture_workflow`, …). A replacement
subclasses the workflow and overrides `perform`:

```ruby
module MyStore
  class AddItem < Spree::Carts::AddItem
    def perform(variant:, cart: nil, **rest)
      super

      # your logic, then the standard result
    end
  end
end

Spree.cart_add_item_workflow = MyStore::AddItem
```

<Note>
Before writing this, check whether a
[hook](/developer/customization/workflows#available-hooks) covers your case —
`carts.add_item.validate` and `carts.add_item.after_item_added` handle most
reasons people replace this class, and they don't need maintaining across
upgrades.
</Note>

<Warning>
A subclass runs its hooks under its **own** key, derived from its class name —
`MyStore::AddItem` fires `my_store.add_item.*`, not `carts.add_item.*`. Hooks
registered on the original key (by you or by an installed extension) stop
firing once you swap the class in. To keep them, declare the original key in
the subclass:

```ruby
class AddItem < Spree::Carts::AddItem
  workflow_key 'carts.add_item'
end
```
</Warning>

## Using dependencies in your code

When you need to use a dependency in your code, you can access it directly via the `Spree` module:

```ruby
# Returns the resolved class (not a string)
Spree.cart_add_item_workflow.call(cart: cart, variant: variant, quantity: 1)

# For API dependencies, use the Spree.api accessor
Spree.api.cart_serializer.new(cart).serializable_hash
```

## Controller level customization

If you need to replace a serializer in a specific API endpoint only, you can create a [code decorator](/developer/customization/decorators):

```bash
mkdir -p app/controllers/spree/api/v3/store && touch app/controllers/spree/api/v3/store/carts_controller_decorator.rb
```

and add the following code to it:

```ruby
module Spree
  module Api
    module V3
      module Store
        module CartsControllerDecorator
          def serializer_class
            MyNewAwesomeCartSerializer
          end
        end

        CartsController.prepend(CartsControllerDecorator)
      end
    end
  end
end
```

This will change the serializer in this API endpoint to `MyNewAwesomeCartSerializer`. Services and workflows are resolved through the global dependencies (e.g. `Spree.cart_add_item_workflow`), so swap those at the application level.

Different API endpoints can have different dependency injection points. You can review their [source code](https://github.com/spree/spree/tree/main/spree/api/app/controllers/spree/api/v3) to see what you can replace.

## API level customization

API serializers have their own injection points under `Spree.api` — Store API serializers (`cart_serializer`, `product_serializer`, …) and Admin API serializers (`admin_order_serializer`, …) — so you can customize one surface without touching the other.

In your Spree initializer (`config/initializers/spree.rb`) please add:

```ruby
Spree.api.cart_serializer = MyNewAwesomeCartSerializer
Spree.api.admin_order_serializer = MyNewAwesomeAdminOrderSerializer
```

This will swap the default serializers for your custom ones within all API endpoints that use them.

## Debugging dependencies

Spree provides rake tasks to help you debug and inspect dependencies:

### List all dependencies

```bash
bin/rake spree:dependencies:list
```

This will output all dependencies with their current values:

```
[CORE]
cart_add_item_workflow          Spree::Carts::AddItem
carts_create_service            Spree::Carts::Create
cart_recalculate_workflow       Spree::Carts::Recalculate [OVERRIDDEN]
...

[API]
cart_serializer                 Spree::Api::V3::CartSerializer
product_serializer              MyApp::ProductSerializer [OVERRIDDEN]
...
```

You can use `grep` to filter results:

```bash
bin/rake spree:dependencies:list | grep cart
```

### Show only overridden dependencies

```bash
bin/rake spree:dependencies:overrides
```

This shows only the dependencies that have been customized, along with their original and current values:

```
[Core OVERRIDES]
cart_recalculate_workflow  Spree::Carts::Recalculate -> MyApp::CartRecalculate (config/initializers/spree.rb:15)

[API OVERRIDES]
product_serializer  Spree::Api::V3::ProductSerializer -> MyApp::ProductSerializer (config/initializers/spree.rb:20)
```

### Validate all dependencies

```bash
bin/rake spree:dependencies:validate
```

This validates that all dependencies can be resolved to valid classes. If any dependency points to a non-existent class, it will report an error:

```
..........F.........
1 invalid dependencies:
  [Core] cart_add_item_workflow: uninitialized constant NonExistentClass
```

## Programmatic introspection

You can also inspect dependencies programmatically:

```ruby
# Check all current values
Spree::Dependencies.current_values
# => [{name: :cart_add_item_workflow, current: MyApp::CartAddItem, default: 'Spree::Carts::AddItem', overridden: true}, ...]

# Check if a specific dependency is overridden
Spree::Dependencies.overridden?(:cart_add_item_workflow)
# => true

# Get override information (where it was set)
Spree::Dependencies.override_info(:cart_add_item_workflow)
# => {value: MyApp::CartAddItem, source: "config/initializers/spree.rb:15", set_at: 2024-01-15 10:30:00}

# Validate all dependencies resolve to valid classes
Spree::Dependencies.validate!
# => true (or raises Spree::DependencyError)
```

## Seams backed by a workflow

Seams backed by a [workflow](/developer/customization/workflows) use a
`*_workflow` name, not `*_service`:

| Legacy name | Current name |
|---|---|
| `cart_add_item_service` | `cart_add_item_workflow` |
| `cart_recalculate_service` | `cart_recalculate_workflow` |
| `carts_complete_service` | `carts_complete_workflow` |
| `carts_upsert_items_service` | `cart_upsert_items_workflow` |
| `cart_merge_strategy` | `cart_merge_workflow` |
| `order_cancel_service` | `order_cancel_workflow` |
| `order_complete_service` | `order_complete_workflow` |
| `fulfillment_create_service` | `fulfillment_create_workflow` |
| `payments_handle_webhook_service` | `payments_handle_webhook_workflow` |
| `shipment_update_service`, `fulfillment_update_service` | `fulfillment_update_workflow` |
| `gift_card_apply_service` | `gift_card_apply_workflow` |
| `gift_card_remove_service` | `gift_card_remove_workflow` |
| `gift_card_redeem_service` | `gift_card_redeem_workflow` |

<Warning>
The legacy names stay readable, but **assigning to one no longer has any
effect** — the override is recorded and a deprecation warning names the seam to
port to. A class written against the old service contract isn't interchangeable
with the workflow the new call sites use, so applying it silently would break
checkout in ways that are hard to trace.

If you override any of these, move to the `*_workflow` name and make sure your
class subclasses the workflow.
</Warning>

Two seams are plain renames with an unchanged contract, so an override set
under the old name is still applied (with a deprecation warning):
`checkout_add_store_credit_service` → `store_credit_apply_service` and
`checkout_remove_store_credit_service` → `store_credit_remove_service`. All
legacy names are removed in Spree 6.1.

## Backwards compatibility

The legacy string-based syntax is still supported for backwards compatibility:

```ruby
# Legacy syntax (still works)
Spree::Dependencies.carts_create_service = 'MyStore::CartCreate'
result = Spree::Dependencies.carts_create_service.constantize

# New syntax (recommended)
Spree.carts_create_service = MyStore::CartCreate
result = Spree.carts_create_service
```

Both syntaxes can coexist, but the new syntax is recommended as it's more concise and provides better error messages at assignment time.

## Default values

Default values can be easily checked by:

1. Using the rake task: `bin/rake spree:dependencies:list`
2. Looking at the source code:
   * [Application (global) dependencies](https://github.com/spree/spree/blob/main/spree/core/lib/spree/core/dependencies.rb)
   * [API level dependencies](https://github.com/spree/spree/blob/main/spree/api/lib/spree/api/dependencies.rb)