class KSUID::Type
Encapsulates the data type for a KSUID
This is the main class that you will interact with in this gem. You will not typically generate these directly, but this is the resulting data type for all of the main generation methods on the {KSUID} module.
A KSUID
type has two pieces of information contained within its byte-encoded data:
-
The timestamp associated with the
KSUID
(stored as the first 4 bytes) -
The payload, or random data, for the
KSUID
(stored as the last 16 bytes)
The type gives you access to several handles into these data.
Attributes
Public Class Methods
Instantiates a new KSUID
type
@api semipublic
@example Generate a new KSUID
for the current second
KSUID::Type.new
@example Generate a new KSUID
for a given timestamp
KSUID::Type.new(time: Time.parse('2017-11-05 15:00:04 UTC'))
@param payload [String, Array<Integer>, nil] the payload for the KSUID
@param time [Time] the timestamp to use for the KSUID
@return [KSUID::Type] the generated KSUID
# File lib/ksuid/type.rb, line 36 def initialize(payload: nil, time: Time.now) payload ||= KSUID.config.random_generator.call byte_encoding = Utils.int_to_bytes(time.to_i - EPOCH_TIME) @uid = byte_encoding.bytes + payload.bytes end
Public Instance Methods
Implements the Comparable interface for sorting KSUIDs
@api private
@param other [KSUID::Type] the other object to compare against @return [Integer] -1 for less than other, 0 for equal to, 1 for greater than other
# File lib/ksuid/type.rb, line 49 def <=>(other) to_time <=> other.to_time end
The payload for the KSUID
, as a hex-encoded string
This is generally useful for comparing against the Go tool
@api public
@example
ksuid = KSUID.from_base62('0vdbMgWkU6slGpLVCqEFwkkZvuW') ksuid.payload #=> "049CC215C099D42B784DBE99341BD79C"
@return [String] a hex-encoded string
# File lib/ksuid/type.rb, line 90 def payload Utils.bytes_to_hex_string(uid.last(BYTES[:payload])) end
The KSUID
as a hex-encoded string
This is generally useful for comparing against the Go tool.
@api public
@example
ksuid = KSUID.from_base62('0vdbMgWkU6slGpLVCqEFwkkZvuW') ksuid.raw #=> "0683F789049CC215C099D42B784DBE99341BD79C"
@return [String] a hex-encoded string
# File lib/ksuid/type.rb, line 106 def raw Utils.bytes_to_hex_string(uid) end
The KSUID
as a byte string
@api public
@example
ksuid = KSUID.from_base62('0vdbMgWkU6slGpLVCqEFwkkZvuW') ksuid.to_bytes
@return [String] a byte string
# File lib/ksuid/type.rb, line 120 def to_bytes Utils.byte_string_from_array(uid) end
The KSUID
as a Unix timestamp
@api public
@example
ksuid = KSUID.from_base62('0vdbMgWkU6slGpLVCqEFwkkZvuW') ksuid.to_i #=> 109311881
@return [Integer] the Unix timestamp for the event (without the epoch shift)
# File lib/ksuid/type.rb, line 134 def to_i Utils.int_from_bytes(uid.first(BYTES[:timestamp])) end