Dependencies

Overview

With Dependencies you can easily replace parts of Spree internals with your custom classes. You can replace Services, Abilities and Serializers. More will come in the future.

Controller level customization

To replace serializers or Services in a specific API endpoint you can create a simple decorator:
Create a app/controllers/my_store/spree/cart_controller_decorator.rb
1
module MyStore
2
module Spree
3
module CartControllerDecorator
4
def resource_serializer
5
MyNewAwesomeCartSerializer
6
end
7
​
8
def add_item_service
9
MyNewAwesomeAddItemToCart
10
end
11
end
12
end
13
end
14
Spree::Api::V2::Storefront::CartController.prepend MyStore::Spree::CartControllerDecorator
Copied!
This will change the serializer in this API endpoint to MyNewAwesomeCartSerializer and also it will swap the default add_item_service to MyNewAwesomeAddItemToCart.
Different API endpoints can have different dependency injection points. You can review their source code to see what you can configure.

API level customization

Storefront and Platform APIs have separate Dependencies injection points so you can easily customize one without touching the other.
In your Spree initializer (config/initializers/spree.rb) please add:
1
Spree::Api::Dependencies.storefront_cart_serializer = 'MyNewAwesomeCartSerializer'
2
Spree::Api::Dependencies.storefront_cart_add_item_service = 'MyNewAwesomeAddItemToCart'
Copied!
This will swap the default Cart serializer and Add Item to Cart service for your custom ones within all Storefront API endpoints that uses those classes.
Values set in the initializer has to be strings, eg. `'MyNewAwesomeAddItemToCart'`

Application (global) customization

You can also inject classes globally to the entire Spree stack. Be careful about this though as this touches every aspect of the application (both APIs, Admin Panel and default Rails frontend if you're using it).
1
Spree::Dependencies.cart_add_item_service = 'MyNewAwesomeAddItemToCart'
Copied!
or
1
Spree.dependencies do |dependencies|
2
dependencies.cart_add_item_service = 'MyNewAwesomeAddItemToCart'
3
end
Copied!
You can mix and match both global and API level customizations:
1
Spree::Dependencies.cart_add_item_service = 'MyNewAwesomeAddItemToCart'
2
Spree::Api::Dependencies.storefront_cart_add_item_service = 'AnotherAddItemToCart'
Copied!
The second line will have precedence over the first one, and the Storefront API will use AnotherAddItemToCart and the rest of the application will use MyNewAwesomeAddItemToCart
Values set in the initializer have to be strings, eg. 'MyNewAwesomeAddItemToCart'

Default values

Default values can be easily checked looking at the source code of Dependencies classes:
Last modified 3mo ago