Sha256: 75fe5440f9f851bcb52c14d6d74e515a3de739f44db70d6f5b4ab43eb3f0125a

Contents?: true

Size: 1.44 KB

Versions: 36

Compression:

Stored size: 1.44 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 order_count > (10**@length / 2)
        else
          break random
        end
      end
    end

    private

    def order_count
      @order_count ||= Spree::Order.count
    end
  end
end

Version data entries

36 entries across 36 versions & 1 rubygems

Version Path
solidus_core-4.4.2 app/models/spree/order/number_generator.rb
solidus_core-4.4.1 app/models/spree/order/number_generator.rb
solidus_core-4.4.0 app/models/spree/order/number_generator.rb
solidus_core-4.3.4 app/models/spree/order/number_generator.rb
solidus_core-4.2.4 app/models/spree/order/number_generator.rb
solidus_core-4.1.5 app/models/spree/order/number_generator.rb
solidus_core-4.3.3 app/models/spree/order/number_generator.rb
solidus_core-4.3.2 app/models/spree/order/number_generator.rb
solidus_core-4.1.4 app/models/spree/order/number_generator.rb
solidus_core-4.3.1 app/models/spree/order/number_generator.rb
solidus_core-4.3.0 app/models/spree/order/number_generator.rb
solidus_core-4.2.3 app/models/spree/order/number_generator.rb
solidus_core-4.1.3 app/models/spree/order/number_generator.rb
solidus_core-4.0.4 app/models/spree/order/number_generator.rb
solidus_core-3.4.6 app/models/spree/order/number_generator.rb
solidus_core-4.0.3 app/models/spree/order/number_generator.rb
solidus_core-4.1.2 app/models/spree/order/number_generator.rb
solidus_core-4.2.2 app/models/spree/order/number_generator.rb
solidus_core-3.4.5 app/models/spree/order/number_generator.rb
solidus_core-4.2.1 app/models/spree/order/number_generator.rb