Module: HasPublicId::Util

Defined in:
lib/has_public_id/util.rb

Constant Summary collapse

DEFAULT_CHAR_SET =
(0..9).collect { |i| i.to_s } + ('A'..'Z').to_a + ('a'..'z').to_a

Class Method Summary collapse

Class Method Details

.char_setObject



4
5
6
# File 'lib/has_public_id/util.rb', line 4

def self.char_set
  @car_set ||= DEFAULT_CHAR_SET
end

.generate_prefix(klass) ⇒ Object



12
13
14
# File 'lib/has_public_id/util.rb', line 12

def self.generate_prefix(klass)
  klass.to_s.demodulize.underscore.first(3)
end

.generate_random_suffix(length) ⇒ Object



7
8
9
10
11
# File 'lib/has_public_id/util.rb', line 7

def self.generate_random_suffix(length)
  (0...length.to_i).map do |i|
    char_set[SecureRandom.random_number(char_set.length)]
  end.join
end

.new_public_id(klass, options = {}) ⇒ Object



15
16
17
18
19
20
21
22
# File 'lib/has_public_id/util.rb', line 15

def self.new_public_id(klass, options = {})
  length = options[:length] || 12
  prefix = options.fetch(:prefix, generate_prefix(klass))
  prefix = nil if !prefix || prefix.empty?
  join_with = options.fetch(:join_with, '-')
  suffix = generate_random_suffix(length)
  [prefix, suffix].compact.join(join_with)
end