Class: ActiveUxid::Hash

Inherits:
Base
  • Object
show all
Defined in:
lib/active_uxid/hash.rb

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Base

#encoding_base

Constructor Details

#initialize(id) ⇒ Hash

Returns a new instance of Hash.



6
7
8
9
# File 'lib/active_uxid/hash.rb', line 6

def initialize(id)
  @id = id
  super()
end

Class Method Details

.decode(id) ⇒ Object



16
17
18
19
# File 'lib/active_uxid/hash.rb', line 16

def self.decode(id)
  klass = new(id)
  klass.decode_uxid
end

.encode(id) ⇒ Object



11
12
13
14
# File 'lib/active_uxid/hash.rb', line 11

def self.encode(id)
  klass = new(id)
  klass.encode_uxid
end

Instance Method Details

#decode_uxidObject



25
26
27
# File 'lib/active_uxid/hash.rb', line 25

def decode_uxid
  (uxid_decode_chars(@id) >> encoding_length) - encoding_salt
end

#encode_uxidObject



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

def encode_uxid
  uxid_encode_chars((@id + encoding_salt) << encoding_length)
end

#uxid_decode_chars(id) ⇒ Object



43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/active_uxid/hash.rb', line 43

def uxid_decode_chars(id)
  pos = 0
  num = 0
  len = id.length
  max = len - 1

  while pos < len
    pow = encoding_base**(max - pos)
    num += encoding_chars.index(id[pos]) * pow
    pos += 1
  end

  num
end

#uxid_encode_chars(id) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/active_uxid/hash.rb', line 29

def uxid_encode_chars(id)
  return '0' if id.zero?
  return nil if id.negative?

  str = ''

  while id.positive?
    str = "#{encoding_chars[id % encoding_base]}#{str}"
    id /= encoding_base
  end

  str
end