Decorators
Decorators allow you to add behavior to Spree classes in your application.
It is highly recommended to use Dependencies instead of decorators. Decorators should be used as a last resort. They can make upgrading Spree more difficult.
Overview
All of Spree’s models, controllers, helpers, etc can easily be extended or overridden to meet your exact requirements using standard Ruby idioms.
Standard practice for including such changes in your application or extension is to create a file within the relevant app/models/spree or app/controllers/spree directory with the original class name with _decorator appended.
Decorating Models
Changing behavior of existing methods
Changing the behavior of existing methods is the most common use case for decorators.
Let’s say you want to change the behavior of the available?
in the Product model.
-
Let’s start with creating a file in
app/models/spree/product_decorator.rb
-
And add the following code to the file:
Adding a new method to the model
You can also add a new method to the model. Or even add validations or any other rails magic methods, see example below.
Adding new associations to Spree models
Assume you want to add a new model called Video
associated to Spree::Product
. Let’s start with creating a database migration:
In the model code add the association to Spree::Product
:
Finally add the association in ProductDecorator
in app/models/spree/product_decorator.rb
:
Decorating Controllers
Adding a custom action to the ProductsController
-
Create a file in
app/controllers/spree/products_controller_decorator.rb
-
Add the following code:
The exact same format can be used to redefine an existing method.
Accessing Product Data
If you extend the Products controller with a new method, you may very well want to access product data in that method. You can do so by using the :load_data before_action
.
:load_data
will use params[:id]
to lookup the product by its permalink.
Was this page helpful?