Solidus provides an out-of-the-box mechanism to generate order numbers. However, sometimes you could be interested in personalizing this mechanism according to your business rules. In this blogpost, I want to show you how to use this feature in favor of your store implementation.
The Configurable order number generator
Solidus has an out-of-the-box class that controls the order number generation called Spree::Order::NumberGenerator
(see on GitHub). By default, this class generates order numbers with the prefix R
and 9 digits after the prefix, such as R051777136
. If you want to modify this behavior you can override the Spree::Config.order_number_generator
method to use a different prefix, order number length, and even use letters in it. For example, if you want to use a 13-character order number with a MAG
prefix you can add it to your spree config file:
Spree::Config.order_number_generator = Spree::Order::NumberGenerator.new(prefix: 'MAG', length: 13, letters: false)
If you need to add specific business rules for your order numbers, you can create your own OrderNumberGenerator
custom class and override Spree::Config.order_number_generator
:
Spree::Config.order_number_generator = MyAwesomeStore::NumberGenerator.new
Using multiple order number generators
Sometimes we need to use different order number generators to identify different kinds of orders in our system (like a subscription order). The order number generator is called inside Spree::Order#generate_order
(see on GitHub) by default. If you need to modify this default behavior you can override this method to use a different order number generator. For example, if you want to use a prefix S
for subscriptions and R
for regular orders you can implement something like:
# config/initializers/spree.rb
Spree::Config.order_number_generator = {
default: Spree::Order::NumberGenerator.new(prefix: 'R', length: 10, letters: false),
subscription: Spree::Order::NumberGenerator.new(prefix: 'S', length: 10, letters: false)
}
# app/models/spree/order_decorator.rb
def generate_order_number
self.number ||= Spree::Config.order_number_generator[:default].generate
end
def generate_subscription_order_number
self.number ||= Spree::Config.order_number_generator[:subscription].generate
end
and call the generate_subscription_order_number
method in your subscription workflow.
Conclusion
Solidus flexibility allows you to create awesome shopping experiences, and as it is an open source project you can see how the features are implemented, so you can use all this knowledge in your favor. If you want to see how the number generation is implemented in solidus you can see the Add a configurable order number generator pull request.