Class: TypeID::UUID

Inherits:
String
  • Object
show all
Defined in:
lib/typeid/uuid.rb,
lib/typeid/uuid/base32.rb

Overview

Represents a UUID. Can be treated as a string.

Defined Under Namespace

Modules: Base32

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(bytes) ⇒ UUID

Initializes a UUID from an array of bytes.

Parameters:

  • bytes (Array<Integer>)

    size 16 byte array



50
51
52
53
54
# File 'lib/typeid/uuid.rb', line 50

def initialize(bytes)
  @bytes = bytes

  super(string)
end

Instance Attribute Details

#bytesArray<Integer> (readonly)

Returns:

  • (Array<Integer>)


8
9
10
# File 'lib/typeid/uuid.rb', line 8

def bytes
  @bytes
end

Class Method Details

.from_base32(string) ⇒ TypeID::UUID

Parses a UUID from a base32 String.

Parameters:

  • string (String)

    base32-encoded UUID

Returns:



29
30
31
# File 'lib/typeid/uuid.rb', line 29

def self.from_base32(string)
  new(TypeID::UUID::Base32.decode(string))
end

.from_string(string) ⇒ TypeID::UUID

Parses a UUID from a raw String.

Parameters:

  • string (String)

    raw UUID

Returns:



37
38
39
40
41
42
43
44
45
# File 'lib/typeid/uuid.rb', line 37

def self.from_string(string)
  bytes = string
    .tr("-", "")
    .chars
    .each_slice(2)
    .map { |pair| pair.join.to_i(16) }

  new(bytes)
end

.generate(timestamp: self.class.timestamp) ⇒ TypeID::UUID

Generates a new UUID, using gem “uuid7”.

Parameters:

  • timestamp (Integer) (defaults to: self.class.timestamp)

    milliseconds since the Unix epoch

Returns:



21
22
23
# File 'lib/typeid/uuid.rb', line 21

def self.generate(timestamp: self.class.timestamp)
  from_string(UUID7.generate(timestamp: timestamp))
end

.timestampInteger

Utility method to generate a timestamp as milliseconds since the Unix epoch.

Returns:

  • (Integer)


13
14
15
# File 'lib/typeid/uuid.rb', line 13

def self.timestamp
  Process.clock_gettime(Process::CLOCK_REALTIME, :millisecond)
end

Instance Method Details

#base32String

Returns the UUID encoded as a base32 String.

Returns:

  • (String)


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

def base32
  TypeID::UUID::Base32.encode(bytes)
end

#inspectString

Returns:

  • (String)


73
74
75
# File 'lib/typeid/uuid.rb', line 73

def inspect
  "#<#{self.class.name} #{to_s}>"
end

#timestampInteger

Returns the timestamp of the UUID as milliseconds since the Unix epoch.

Returns:

  • (Integer)


66
67
68
69
70
# File 'lib/typeid/uuid.rb', line 66

def timestamp
  bytes[0..5]
    .map.with_index { |byte, index| byte << (5 - index) * 8 }
    .inject(:|)
end