Branch: master
Find file Copy path
83c0803 Jan 28, 2019
1 contributor

Users who have contributed to this file

86 lines (59 sloc) 2.95 KB
title section
Using Dependendencies system

Using Dependendencies system


Dependendencies is a a new way to customize Spree. 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.

Dependencies are available in [Spree 3.7](/release_notes/3_7_0.html) and later.

Controller level customization

To replace serializers or Services in a specific API endpoint you can create a simple decorator:

Create a app/controllers/spree/api/v2/storefront/cart_controller_decorator.rb

  module MyCartControllerDecorator
    def resource_serializer

    def add_item_service
  Spree::Api::V2::Storefront::CartController.prepend MyCartControllerDecorator

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:

Spree::Api::Dependencies[:storefront_cart_serializer] = 'MyNewAwesomeCartSerializer'
Spree::Api::Dependencies[:storefront_cart_add_item_service] = 'MyNewAwesomeAddItemToCart'

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).

Spree::Dependencies[:cart_add_item_service] = 'MyNewAwesomeAddItemToCart'


Spree.dependencies do |dependencies|
  dependencies.cart_add_item_service = 'MyNewAwesomeAddItemToCart'

You can mix and match both global and API level customizations:

Spree::Dependencies[:cart_add_item_service] = 'MyNewAwesomeAddItemToCart'
Spree::Api::Dependencies[:storefront_cart_add_item_service] = 'AnotherAddItemToCart'

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 has to be strings, eg. `MyNewAwesomeAddItemToCart`

Default values

Default values can be easily checked looking at the source code of Dependencies classes: