Class: ActiveUxid::Ulid

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

Constant Summary

Constants inherited from Base

Base::ENCODING_LENGTH

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeUlid

Returns a new instance of Ulid.



9
# File 'lib/active_uxid/ulid.rb', line 9

def initialize; end

Class Method Details

.encodeObject



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

def self.encode
  klass = new
  klass.uxid_encode
end

Instance Method Details

#uxid_bytesObject



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

def uxid_bytes
  "#{uxid_unixtime_48bit}#{SecureRandom.random_bytes(10)}"
end

#uxid_encodeObject



16
17
18
19
20
21
# File 'lib/active_uxid/ulid.rb', line 16

def uxid_encode
  (1..ENCODING_LENGTH).reduce('') do |str, num|
    shift = 128 - 5 * num
    "#{str}#{ENCODING_CHARS[(uxid_octect >> shift) & 0x1f]}"
  end
end

#uxid_octectObject



27
28
29
30
# File 'lib/active_uxid/ulid.rb', line 27

def uxid_octect
  (hi, lo) = uxid_bytes.unpack('Q>Q>')
  (hi << 64) | lo
end

#uxid_unixtime_48bitObject



36
37
38
# File 'lib/active_uxid/ulid.rb', line 36

def uxid_unixtime_48bit
  [uxid_unixtime_flex].pack('Q>')[2..-1]
end

#uxid_unixtime_flexObject



32
33
34
# File 'lib/active_uxid/ulid.rb', line 32

def uxid_unixtime_flex
  (Time.current.to_f * 10_000).to_i
end