Class: Xid
- Inherits:
-
Object
show all
- Defined in:
- lib/ruby_xid.rb
Defined Under Namespace
Classes: Base32, Generator
Constant Summary
collapse
- RAW_LEN =
12
- TRIM_LEN =
20
- @@generator =
nil
Class Method Summary
collapse
Instance Method Summary
collapse
Constructor Details
#initialize(id = nil) ⇒ Xid
Returns a new instance of Xid.
14
15
16
17
|
# File 'lib/ruby_xid.rb', line 14
def initialize(id = nil)
@@generator ||= Generator.new(init_rand_int, real_machine_id)
@byte_str = id ? id.map(&:chr).join('') : @@generator.next_xid
end
|
Class Method Details
.from_string(str) ⇒ Object
98
99
100
101
102
103
104
105
106
107
108
109
|
# File 'lib/ruby_xid.rb', line 98
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
88
89
90
91
|
# File 'lib/ruby_xid.rb', line 88
def <(other_xid)
to_s < other_xid.to_s
end
|
#==(other_xid) ⇒ Object
83
84
85
86
|
# File 'lib/ruby_xid.rb', line 83
def ==(other_xid)
to_s == other_xid.to_s
end
|
#>(other_xid) ⇒ Object
93
94
95
96
|
# File 'lib/ruby_xid.rb', line 93
def >(other_xid)
to_s > other_xid.to_s
end
|
#bytes ⇒ Object
66
67
68
69
|
# File 'lib/ruby_xid.rb', line 66
def bytes
@byte_str
end
|
#counter ⇒ Object
34
35
36
37
|
# File 'lib/ruby_xid.rb', line 34
def counter
value[9] << 16 | value[10] << 8 | value[11]
end
|
#datetime ⇒ Object
44
45
46
|
# File 'lib/ruby_xid.rb', line 44
def datetime
Time.at(time).to_datetime
end
|
#init_rand_int ⇒ Object
71
72
73
74
|
# File 'lib/ruby_xid.rb', line 71
def init_rand_int
SecureRandom.random_number(16_777_215)
end
|
#inspect ⇒ Object
53
54
55
|
# File 'lib/ruby_xid.rb', line 53
def inspect
"Xid('#{string}')"
end
|
#machine ⇒ Object
39
40
41
42
|
# File 'lib/ruby_xid.rb', line 39
def machine
value[4..6].map(&:chr).join('')
end
|
#next ⇒ Object
19
20
21
22
23
|
# File 'lib/ruby_xid.rb', line 19
def next
@string = @value = nil
@byte_str = @@generator.next_xid
string
end
|
#pid ⇒ Object
29
30
31
32
|
# File 'lib/ruby_xid.rb', line 29
def pid
(value[7] << 8 | value[8])
end
|
#real_machine_id ⇒ Object
76
77
78
79
80
81
|
# File 'lib/ruby_xid.rb', line 76
def real_machine_id
Digest::MD5.digest(Socket.gethostname).unpack('N')[0]
rescue
init_rand_int
end
|
#time ⇒ Object
48
49
50
51
|
# File 'lib/ruby_xid.rb', line 48
def time
value[0] << 24 | value[1] << 16 | value[2] << 8 | value[3]
end
|
#to_s ⇒ Object
57
58
59
|
# File 'lib/ruby_xid.rb', line 57
def to_s
string
end
|
#value ⇒ Object
25
26
27
|
# File 'lib/ruby_xid.rb', line 25
def value
@value ||= @byte_str.chars.map(&:ord)
end
|