class DatashiftJourney::ReferenceGenerator

Constants

BASE
DEFAULT_LENGTH
LETTERS
NUMBERS

Attributes

length[RW]
prefix[RW]

Public Class Methods

new(options) click to toggle source
# 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

Public Instance Methods

included(host) click to toggle source
# 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

Private Instance Methods

new_candidate(length) click to toggle source
# File lib/datashift_journey/reference_generator.rb, line 47
def new_candidate(length)
  @prefix + Array.new(length) { @candidates.sample(random: @random) }.join
end