Class: Spree::Core::NumberGenerator

Inherits:
Module
  • Object
show all
Defined in:
lib/spree/core/number_generator.rb

Constant Summary collapse

BASE =
10
DEFAULT_LENGTH =
9

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ NumberGenerator

Returns a new instance of NumberGenerator.



9
10
11
12
13
# File 'lib/spree/core/number_generator.rb', line 9

def initialize(options)
  @prefix     = options.fetch(:prefix)
  @length     = options.fetch(:length, DEFAULT_LENGTH)
  @letters    = options[:letters]
end

Instance Attribute Details

#lengthObject

Returns the value of attribute length.



7
8
9
# File 'lib/spree/core/number_generator.rb', line 7

def length
  @length
end

#prefixObject

Returns the value of attribute prefix.



7
8
9
# File 'lib/spree/core/number_generator.rb', line 7

def prefix
  @prefix
end

Instance Method Details



31
32
33
34
35
36
37
38
39
40
41
# File 'lib/spree/core/number_generator.rb', line 31

def generate_permalink(host)
  length = @length

  loop do
    candidate = new_candidate(length)
    return candidate unless host.exists?(number: candidate)

    # If over half of all possible options are taken add another digit.
    length += 1 if host.count > Rational(BASE**length, 2)
  end
end

#included(host) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/spree/core/number_generator.rb', line 15

def included(host)
  generator_instance = self

  host.class_eval do
    before_validation do |instance|
      instance.number ||= generate_permalink(host)
    end

    define_singleton_method(:number_generator) { generator_instance }

    def generate_permalink(host)
      host.number_generator.generate_permalink(host)
    end
  end
end

#new_candidate(length) ⇒ Object



43
44
45
46
# File 'lib/spree/core/number_generator.rb', line 43

def new_candidate(length)
  characters = @letters ? 36 : 10
  @prefix + SecureRandom.random_number(characters**length).to_s(characters).rjust(length, '0').upcase
end