Class: Spree::Core::NumberGenerator
- Inherits:
-
Module
- Object
- Module
- Spree::Core::NumberGenerator
- Defined in:
- lib/spree/core/number_generator.rb
Constant Summary collapse
- BASE =
10
- DEFAULT_LENGTH =
9
Instance Attribute Summary collapse
-
#length ⇒ Object
Returns the value of attribute length.
-
#prefix ⇒ Object
Returns the value of attribute prefix.
Instance Method Summary collapse
- #generate_permalink(host) ⇒ Object
- #included(host) ⇒ Object
-
#initialize(options) ⇒ NumberGenerator
constructor
A new instance of NumberGenerator.
- #new_candidate(length) ⇒ Object
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() @prefix = .fetch(:prefix) @length = .fetch(:length, DEFAULT_LENGTH) @letters = [:letters] end |
Instance Attribute Details
#length ⇒ Object
Returns the value of attribute length.
7 8 9 |
# File 'lib/spree/core/number_generator.rb', line 7 def length @length end |
#prefix ⇒ Object
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
#generate_permalink(host) ⇒ Object
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 |