Class: TUID

Inherits:
Object
  • Object
show all
Includes:
Comparable
Defined in:
lib/tuid.rb,
lib/tuid/version.rb

Overview

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.

Constant Summary collapse

VERSION =
"0.1.0"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeObject #initialize(data) ⇒ Object #initialize(time) ⇒ Object

Initialize a new TUID

Overloads:

  • #initializeObject

    Returns Random TUID based on the current time.

  • #initialize(data) ⇒ Object

    Returns TUID object equivalent to the passed string.

    Parameters:

    • data (String)

      TUID string representation.

  • #initialize(time) ⇒ Object

    Returns Random TUID using the given generation time.

    Parameters:

    • time (Time)

      Reference time.



31
32
33
34
35
36
37
38
39
40
41
42
# 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

Instance Attribute Details

#bytesObject (readonly)

TUID binary representation



16
17
18
# File 'lib/tuid.rb', line 16

def bytes
  @bytes
end

Instance Method Details

#<=>(other) ⇒ -1, ...

Compares two TUIDs.

Returns:

  • (-1, 0, 1)

    the compare result.



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

def <=>(other)
  self.bytes <=> other.bytes
end

#eql?(other) ⇒ Boolean

Compare two TUID objects

Returns:

  • (Boolean)


72
73
74
# File 'lib/tuid.rb', line 72

def eql?(other)
  other.instance_of?(self.class) && self == other
end

#inspectObject

Console friendly representation



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

def inspect
  "#<#{self.class.name} #{to_s} (#{time.utc})>"
end

#timeTime

Extract the time at which the TUID was generated.

Returns:

  • (Time)

    the generation time.



67
68
69
# File 'lib/tuid.rb', line 67

def time
  Time.at(*bytes.unpack("N"))
end

#to_sString Also known as: to_str

Get the TUID in UUID string format.

Returns:

  • (String)

    formatted as XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX



59
60
61
# File 'lib/tuid.rb', line 59

def to_s
  "%08x-%04x-%04x-%04x-%04x%08x" % bytes.unpack("NnnnnN")
end