Sha256: 95a2ff0956a68789a5e1487e6f1d2a07fbfe3669b9fa7409658023a70c8c9191

Contents?: true

Size: 1.36 KB

Versions: 97

Compression:

Stored size: 1.36 KB

Contents

# frozen_string_literal: true

module Spree
  # 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
  #
  class Order::NumberGenerator
    attr_reader :letters, :prefix

    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

    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
  end
end

Version data entries

97 entries across 97 versions & 2 rubygems

Version Path
solidus_core-3.2.9 app/models/spree/order/number_generator.rb
solidus_core-3.2.8 app/models/spree/order/number_generator.rb
solidus_core-3.2.7 app/models/spree/order/number_generator.rb
solidus_core-3.2.6 app/models/spree/order/number_generator.rb
solidus_core-3.1.9 app/models/spree/order/number_generator.rb
solidus_core-3.2.5 app/models/spree/order/number_generator.rb
solidus_core-3.2.4 app/models/spree/order/number_generator.rb
solidus_core-3.2.3 app/models/spree/order/number_generator.rb
solidus_core-3.1.8 app/models/spree/order/number_generator.rb
solidus_core-3.0.8 app/models/spree/order/number_generator.rb
solidus_core-3.2.2 app/models/spree/order/number_generator.rb
solidus_core-3.2.1 app/models/spree/order/number_generator.rb
solidus_core-3.2.0 app/models/spree/order/number_generator.rb
solidus_core-3.2.0.alpha app/models/spree/order/number_generator.rb
solidus_core-3.0.7 app/models/spree/order/number_generator.rb
solidus_core-2.11.17 app/models/spree/order/number_generator.rb
solidus_core-3.1.7 app/models/spree/order/number_generator.rb
solidus_core-2.11.16 app/models/spree/order/number_generator.rb
solidus_core-3.0.6 app/models/spree/order/number_generator.rb
solidus_core-3.1.6 app/models/spree/order/number_generator.rb