class TUID
TUID
value.
TUIDs are values compatible with UUID
They share the same base format so can be used instead of them. The main property of them is that they are prefixed by the time they were generated. This allow them to be sorted and behave better on database indexes.
Constants
- VERSION
Attributes
bytes[R]
TUID
binary representation
Public Class Methods
new(data=nil)
click to toggle source
Initialize a new TUID
@overload initialize
@return Random TUID based on the current time
@overload initialize(data)
@param data [String] TUID string representation. @return TUID object equivalent to the passed string
@overload initialize(time)
@param time [Time] Reference time. @return Random TUID using the given generation time.
# File lib/tuid.rb, line 31 def initialize(data=nil) @bytes = case data when TUID data.bytes when String bytes_from_string(data) when Time, NilClass random_bytes_with_time(data || Time.now) else raise type_error(data, "invalid type") end.freeze end
Public Instance Methods
<=>(other)
click to toggle source
Compares two TUIDs.
@return [-1,0,1] the compare result.
# File lib/tuid.rb, line 47 def <=>(other) self.bytes <=> other.bytes end
eql?(other)
click to toggle source
Compare two TUID
objects
# File lib/tuid.rb, line 72 def eql?(other) other.instance_of?(self.class) && self == other end
inspect()
click to toggle source
Console friendly representation
# File lib/tuid.rb, line 52 def inspect "#<#{self.class.name} #{to_s} (#{time.utc})>" end
time()
click to toggle source
Extract the time at which the TUID
was generated.
@return [Time] the generation time.
# File lib/tuid.rb, line 67 def time Time.at(*bytes.unpack("N")) end
Private Instance Methods
bytes_from_string(string)
click to toggle source
Parse bytes from String
# File lib/tuid.rb, line 79 def bytes_from_string(string) case string.length when 16 string.frozen? ? string : string.dup when 36 elements = string.split("-") raise type_error(string, "malformed UUID representation") if elements.size != 5 [elements.join].pack('H32') else raise type_error(string, "invalid bytecount") end end
random_bytes_with_time(time)
click to toggle source
Generate bytes string with the given time
# File lib/tuid.rb, line 93 def random_bytes_with_time(time) bytes = [ time.to_i ] + SecureRandom.random_bytes(12).unpack("nnnnN") bytes[2] = (bytes[2] & 0x0fff) | 0x4000 bytes[3] = (bytes[3] & 0x3fff) | 0x8000 bytes.pack("NnnnnN") end
type_error(source,error)
click to toggle source
Create a formatted type error.
# File lib/tuid.rb, line 104 def type_error(source,error) TypeError.new("Expected #{source.inspect} to cast to a #{self.class} (#{error})") end