Class: NeatIds::NeatId

Inherits:
Object
  • Object
show all
Defined in:
lib/neat_ids/neat_id.rb

Constant Summary collapse

TOKEN =
123

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(model, prefix, min_length: NeatIds.minimum_length, alphabet: NeatIds.alphabet, delimiter: NeatIds.delimiter, **options) ⇒ NeatId



7
8
9
10
11
# File 'lib/neat_ids/neat_id.rb', line 7

def initialize(model, prefix, min_length: NeatIds.minimum_length, alphabet: NeatIds.alphabet, delimiter: NeatIds.delimiter, **options)
  @prefix = prefix.to_s
  @delimiter = delimiter.to_s
  @sqids = Sqids.new( min_length: min_length, alphabet: alphabet)
end

Instance Attribute Details

#prefixObject (readonly)

Returns the value of attribute prefix.



3
4
5
# File 'lib/neat_ids/neat_id.rb', line 3

def prefix
  @prefix
end

#sqidsObject (readonly)

Returns the value of attribute sqids.



3
4
5
# File 'lib/neat_ids/neat_id.rb', line 3

def sqids
  @sqids
end

Instance Method Details

#decode(id, fallback: false) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/neat_ids/neat_id.rb', line 22

def decode(id, fallback: false)
  fallback_value = fallback ? id : nil
  _, id_without_prefix = NeatIds.split_id(id, @delimiter)
  decoded_hashid = @sqids.decode(id_without_prefix)

  if !valid?(decoded_hashid)
    fallback_value
  else
    _, *ids = decoded_hashid
    if ids.size == 4 && ids.all? { |n| n.is_a?(Integer) && n >= 0 && n <= 0xFFFFFFFF }
      ints_to_uuid(ids)
    else
      (ids.size == 1) ? ids.first : ids
    end
  end
end

#encode(id) ⇒ Object



13
14
15
16
17
18
19
20
# File 'lib/neat_ids/neat_id.rb', line 13

def encode(id)
  return if id.nil?
  if uuid?(id)
    nums = uuid_to_ints(id)
    return @prefix + @delimiter + @sqids.encode([TOKEN] + nums)
  end
  @prefix + @delimiter + @sqids.encode([TOKEN] + Array.wrap(id))
end