class Xid
Constants
- RAW_LEN
Public Class Methods
from_string(str)
click to toggle source
# File lib/ruby_xid.rb, line 80 def self.from_string(str) raise 'Invalid Xid' if str.nil? || !str.match(/^[a-v0-9]{20}$/i) val = Base32.b32decode(str) value_check = val.select { |x| x >= 0 && x <= 255 } (value_check.length..RAW_LEN - 1).each do |i| value_check[i] = false end raise 'Invalid Xid' unless value_check.all? Object.const_get(name).new(val) end
new(id = nil)
click to toggle source
# File lib/ruby_xid.rb, line 13 def initialize(id = nil) @@generator ||= Generator.new(init_rand_int, real_machine_id) @value = id ? id : @@generator.generate.unpack('C12') end
Public Instance Methods
<(other_xid)
click to toggle source
# File lib/ruby_xid.rb, line 70 def <(other_xid) # type: (Xid) -> bool to_s < other_xid.to_s end
==(other_xid)
click to toggle source
# File lib/ruby_xid.rb, line 65 def ==(other_xid) # type: (Xid) -> bool to_s == other_xid.to_s end
>(other_xid)
click to toggle source
# File lib/ruby_xid.rb, line 75 def >(other_xid) # type: (Xid) -> bool to_s > other_xid.to_s end
bytes()
click to toggle source
# File lib/ruby_xid.rb, line 60 def bytes # type: () -> str @value.pack('c12') end
counter()
click to toggle source
# File lib/ruby_xid.rb, line 33 def counter # type: () -> int value[9] << 16 | value[10] << 8 | value[11] end
datetime()
click to toggle source
# File lib/ruby_xid.rb, line 43 def datetime Time.at(time).to_datetime end
inspect()
click to toggle source
# File lib/ruby_xid.rb, line 52 def inspect "Xid('#{string}')" end
machine()
click to toggle source
# File lib/ruby_xid.rb, line 38 def machine # type: () -> str value[4..6].map(&:chr).join('') end
next()
click to toggle source
# File lib/ruby_xid.rb, line 18 def next @string = nil @value = @@generator.generate.unpack('C12') string end
pid()
click to toggle source
# File lib/ruby_xid.rb, line 28 def pid # type: () -> int (value[7] << 8 | value[8]) end
time()
click to toggle source
# File lib/ruby_xid.rb, line 47 def time # type: () -> int value[0] << 24 | value[1] << 16 | value[2] << 8 | value[3] end
to_s()
click to toggle source
# File lib/ruby_xid.rb, line 56 def to_s string end
value()
click to toggle source
# File lib/ruby_xid.rb, line 24 def value @value end
Private Instance Methods
init_rand_int()
click to toggle source
# File lib/ruby_xid.rb, line 100 def init_rand_int # type: () -> int SecureRandom.random_number(16_777_215) end
real_machine_id()
click to toggle source
# File lib/ruby_xid.rb, line 105 def real_machine_id # type: () -> int Digest::MD5.digest(Socket.gethostname).unpack('N')[0] rescue init_rand_int end
string()
click to toggle source
# File lib/ruby_xid.rb, line 95 def string # type: () -> str @string ||= Base32.b32encode(value) end