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
generate_permalink(host)
click to toggle source
# File lib/datashift_journey/reference_generator.rb, line 35 def generate_permalink(host) length = @length loop do candidate = new_candidate(length) return candidate unless host.exists?(reference: candidate) # If over half of all possible options are taken add another digit. length += 1 if host.count > Rational(BASE**length, 2) end end
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