Class: DatashiftJourney::ReferenceGenerator

Inherits:
Module
  • Object
show all
Defined in:
lib/datashift_journey/reference_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) ⇒ ReferenceGenerator

Returns a new instance of ReferenceGenerator.



11
12
13
14
15
16
# File 'lib/datashift_journey/reference_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/datashift_journey/reference_generator.rb', line 9

def length
  @length
end

#prefixObject

Returns the value of attribute prefix.



9
10
11
# File 'lib/datashift_journey/reference_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/datashift_journey/reference_generator.rb', line 18

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

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

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

    define_singleton_method(:reference_generator) { generator_instance }
  end
end