Class: ULID::Identifier

Inherits:
Object
  • Object
show all
Includes:
Compare, Generate, Parse
Defined in:
lib/ulid/identifier.rb

Constant Summary

Constants included from Constants

Constants::B32REF, Constants::ENCODING, Constants::MAX_ENTROPY, Constants::MAX_TIME, Constants::MIN_ENTROPY, Constants::MIN_TIME

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Compare

#<, #<=>, #>

Methods included from Generate

#encode32, #millisecond_time, #random_bytes, #time_bytes

Methods included from Parse

#decode, #unpack_decoded_bytes

Constructor Details

#initialize(start = nil, seed = nil) ⇒ ULID::Identifier

Create a new instance of a ULID::Identifier.

Parameters:

  • start (ULID::Instance, String, Time, or nil) (defaults to: nil)

    if ULID instance or string is given, initialize to the exact same value. If Time is given, generate a new ULID for that time, if no argument is given, generate a new ULID at the current system time.

  • seed (String or nil) (defaults to: nil)

    a 10-byte, Encoding::ASCII_8BIT encoded string. The easiest way to generate a seed is to call SecureRandom.random_bytes(10)



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/ulid/identifier.rb', line 22

def initialize(start = nil, seed = nil)
  case start
  when self.class
    @time = start.time
    @seed = start.seed
  when NilClass, Time
    @time = (start || Time.now).utc
    if seed == nil
      @seed = random_bytes
    else
      if seed.size != 10 || seed.encoding != Encoding::ASCII_8BIT
        raise ArgumentError.new("seed error, seed value must be 10 bytes encoded as Encoding::ASCII_8BIT")
      end
      @seed = seed
    end
  when String
    if start.size != 26
      raise ArgumentError.new("invalid ULID string, must be 26 characters")
    end

    # parse string into bytes
    @ulid = start.upcase
    @bytes = decode(@ulid)

    @time, @seed = unpack_decoded_bytes(@bytes)
  else
    # unrecognized initial values type given, just generate fresh ULID
    @time = Time.now.utc
    @seed = random_bytes
  end

  if @bytes.nil?
    # an ASCII_8BIT encoded string, should be 16 bytes
    @bytes = time_bytes + @seed
  end

  if @ulid.nil?
    # the lexically sortable Base32 string we actually care about
    @ulid = encode32
  end
end

Instance Attribute Details

#bytesObject (readonly)

Returns the value of attribute bytes.



11
12
13
# File 'lib/ulid/identifier.rb', line 11

def bytes
  @bytes
end

#seedObject (readonly)

Returns the value of attribute seed.



11
12
13
# File 'lib/ulid/identifier.rb', line 11

def seed
  @seed
end

#timeObject (readonly)

Returns the value of attribute time.



11
12
13
# File 'lib/ulid/identifier.rb', line 11

def time
  @time
end

#ulidObject (readonly)

Returns the value of attribute ulid.



11
12
13
# File 'lib/ulid/identifier.rb', line 11

def ulid
  @ulid
end