Module: CoolId

Defined in:
lib/cool_id.rb,
lib/cool_id/version.rb

Defined Under Namespace

Modules: Model Classes: Config, Id, MaxRetriesExceededError, NotConfiguredError, Registry

Constant Summary collapse

DEFAULT_SEPARATOR =
"_"
DEFAULT_ALPHABET =
"0123456789abcdefghijklmnopqrstuvwxyz"
DEFAULT_LENGTH =
12
DEFAULT_MAX_RETRIES =
1000
VERSION =
"0.1.9"

Class Attribute Summary collapse

Class Method Summary collapse

Class Attribute Details

.alphabetObject

Returns the value of attribute alphabet.



21
22
23
# File 'lib/cool_id.rb', line 21

def alphabet
  @alphabet
end

.id_fieldObject

Returns the value of attribute id_field.



21
22
23
# File 'lib/cool_id.rb', line 21

def id_field
  @id_field
end

.lengthObject

Returns the value of attribute length.



21
22
23
# File 'lib/cool_id.rb', line 21

def length
  @length
end

.max_retriesObject

Returns the value of attribute max_retries.



21
22
23
# File 'lib/cool_id.rb', line 21

def max_retries
  @max_retries
end

.separatorObject

Returns the value of attribute separator.



21
22
23
# File 'lib/cool_id.rb', line 21

def separator
  @separator
end

Class Method Details

.configure {|_self| ... } ⇒ Object

Yields:

  • (_self)

Yield Parameters:

  • _self (CoolId)

    the object that the method was called on



23
24
25
# File 'lib/cool_id.rb', line 23

def configure
  yield self
end

.generate_id(config) ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/cool_id.rb', line 39

def generate_id(config)
  alphabet = config.alphabet || @alphabet
  length = config.length || @length
  max_retries = config.max_retries || @max_retries

  retries = 0
  loop do
    nano_id = Nanoid.generate(size: length, alphabet: alphabet)
    full_id = "#{config.prefix}#{separator}#{nano_id}"
    if !config.model_class.exists?(id: full_id)
      return full_id
    end

    retries += 1
    if retries >= max_retries
      raise MaxRetriesExceededError, "Failed to generate a unique ID after #{max_retries} attempts"
    end
  end
end

.locate(id) ⇒ Object



174
175
176
# File 'lib/cool_id.rb', line 174

def self.locate(id)
  registry.locate(id)
end

.parse(id) ⇒ Object



178
179
180
# File 'lib/cool_id.rb', line 178

def self.parse(id)
  registry.parse(id)
end

.registryObject



35
36
37
# File 'lib/cool_id.rb', line 35

def registry
  @prefix_map ||= Registry.new
end

.reset_configurationObject



27
28
29
30
31
32
33
# File 'lib/cool_id.rb', line 27

def reset_configuration
  self.separator = DEFAULT_SEPARATOR
  self.alphabet = DEFAULT_ALPHABET
  self.length = DEFAULT_LENGTH
  self.max_retries = DEFAULT_MAX_RETRIES
  self.id_field = nil
end

.resolve_cool_id_field(model_class) ⇒ Object



59
60
61
# File 'lib/cool_id.rb', line 59

def resolve_cool_id_field(model_class)
  model_class.cool_id_config&.id_field || CoolId.id_field || model_class.primary_key
end