Class: Xid

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

Defined Under Namespace

Classes: Base32, Generator

Constant Summary collapse

RAW_LEN =
12
@@generator =
nil

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(id = nil) ⇒ Xid

Returns a new instance of Xid.



13
14
15
16
# 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_data.unpack('C12')
end

Class Method Details

.from_string(str) ⇒ Object



80
81
82
83
84
85
86
87
88
89
90
91
# File 'lib/ruby_xid.rb', line 80

def self.from_string(str)
  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

Instance Method Details

#<(other_xid) ⇒ Object



70
71
72
73
# File 'lib/ruby_xid.rb', line 70

def <(other_xid)
  # type: (Xid) -> bool
  to_s < other_xid.to_s
end

#==(other_xid) ⇒ Object



65
66
67
68
# File 'lib/ruby_xid.rb', line 65

def ==(other_xid)
  # type: (Xid) -> bool
  to_s == other_xid.to_s
end

#>(other_xid) ⇒ Object



75
76
77
78
# File 'lib/ruby_xid.rb', line 75

def >(other_xid)
  # type: (Xid) -> bool
  to_s > other_xid.to_s
end

#bytesObject



60
61
62
63
# File 'lib/ruby_xid.rb', line 60

def bytes
  # type: () -> str
  @value.map(&:chr).join('')
end

#counterObject



33
34
35
36
# File 'lib/ruby_xid.rb', line 33

def counter
  # type: () -> int
  value[9] << 16 | value[10] << 8 | value[11]
end

#datetimeObject



43
44
45
# File 'lib/ruby_xid.rb', line 43

def datetime
  Time.at(time).to_datetime
end

#inspectObject



52
53
54
# File 'lib/ruby_xid.rb', line 52

def inspect
  "Xid('#{string}')"
end

#machineObject



38
39
40
41
# File 'lib/ruby_xid.rb', line 38

def machine
  # type: () -> str
  value[4..6].map(&:chr).join('')
end

#nextObject



18
19
20
21
22
# File 'lib/ruby_xid.rb', line 18

def next
  @string = nil
  @value = @@generator.generate_data.unpack('C12')
  string
end

#pidObject



28
29
30
31
# File 'lib/ruby_xid.rb', line 28

def pid
  # type: () -> int
  (value[7] << 8 | value[8])
end

#timeObject



47
48
49
50
# File 'lib/ruby_xid.rb', line 47

def time
  # type: () -> int
  value[0] << 24 | value[1] << 16 | value[2] << 8 | value[3]
end

#to_sObject



56
57
58
# File 'lib/ruby_xid.rb', line 56

def to_s
  string
end

#valueObject



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

def value
  @value
end