Class: Spree::Order::NumberGenerator

Inherits:
Object
  • Object
show all
Defined in:
app/models/spree/order/number_generator.rb

Overview

Generates order numbers

In order to change the way your order numbers get generated you can either set your own instance of this class in your stores configuration with different options:

Spree::Config.order_number_generator = Spree::Order::NumberGenerator.new(
  prefix: 'B',
  lenght: 8,
  letters: false
)

or create your own class:

Spree::Config.order_number_generator = My::OrderNumberGenerator.new

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ NumberGenerator

Returns a new instance of NumberGenerator



22
23
24
25
26
# File 'app/models/spree/order/number_generator.rb', line 22

def initialize(options = {})
  @length = options[:length] || Spree::Order::ORDER_NUMBER_LENGTH
  @letters = options[:letters] || Spree::Order::ORDER_NUMBER_LETTERS
  @prefix = options[:prefix] || Spree::Order::ORDER_NUMBER_PREFIX
end

Instance Attribute Details

#lettersObject (readonly)

Returns the value of attribute letters



20
21
22
# File 'app/models/spree/order/number_generator.rb', line 20

def letters
  @letters
end

#prefixObject (readonly)

Returns the value of attribute prefix



20
21
22
# File 'app/models/spree/order/number_generator.rb', line 20

def prefix
  @prefix
end

Instance Method Details

#generateObject



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'app/models/spree/order/number_generator.rb', line 28

def generate
  possible = (0..9).to_a
  possible += ('A'..'Z').to_a if letters

  loop do
    # Make a random number.
    random = "#{prefix}#{(0...@length).map { possible.sample }.join}"
    # Use the random number if no other order exists with it.
    if Spree::Order.exists?(number: random)
      # If over half of all possible options are taken add another digit.
      @length += 1 if Spree::Order.count > (10**@length / 2)
    else
      break random
    end
  end
end