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
NUMBERS =
(0..9).to_a.freeze
LETTERS =
('A'..'Z').to_a.freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ NumberGenerator

Returns a new instance of NumberGenerator.



11
12
13
14
15
16
# File 'lib/spree/core/number_generator.rb', line 11

def initialize(options)
  @random     = Random.new
  @prefix     = options.fetch(:prefix)
  @length     = options.fetch(:length, DEFAULT_LENGTH)
  @candidates = NUMBERS + (options[:letters] ? LETTERS : [])
end

Instance Attribute Details

#lengthObject

Returns the value of attribute length.



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

def length
  @length
end

#prefixObject

Returns the value of attribute prefix.



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

def prefix
  @prefix
end

Instance Method Details

#included(host) ⇒ Object



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

def included(host)
  generator_method   = method(:generate_permalink)
  generator_instance = self

  host.class_eval do
    validates(:number, presence: true, uniqueness: { allow_blank: true })

    before_validation do |instance|
      instance.number ||= generator_method.call(host)
    end

    define_singleton_method(:number_generator) { generator_instance }
  end
end