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.



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

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

Class Method Details

.decode(id) ⇒ Object



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

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

.encode(id) ⇒ Object



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

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

Instance Method Details

#decode_uxidObject



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

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

#encode_uxidObject



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

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

#uxid_decode_chars(id) ⇒ Object



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

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



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

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