class ULID::MonotonicGenerator

Attributes

prev[R]

@return [ULID, nil]

Public Class Methods

new() click to toggle source
Calls superclass method
# File lib/ulid/monotonic_generator.rb, line 15
def initialize
  super()
  @prev = nil
end

Public Instance Methods

freeze() click to toggle source

@raise [TypeError] always raises exception and does not freeze self @return [void]

# File lib/ulid/monotonic_generator.rb, line 70
def freeze
  raise TypeError, "cannot freeze #{self.class}"
end
generate(moment: ULID.current_milliseconds) click to toggle source

@param [Time, Integer] moment @return [ULID] @raise [OverflowError] if the entropy part is larger than the ULID limit in same milliseconds @raise [UnexpectedError] if the generated ULID is an invalid value in monotonicity spec.

Basically will not happen. Just means this feature prefers error rather than invalid value.
# File lib/ulid/monotonic_generator.rb, line 31
def generate(moment: ULID.current_milliseconds)
  synchronize do
    unless @prev
      @prev = ULID.generate(moment: moment)
      return @prev
    end

    milliseconds = ULID.milliseconds_from_moment(moment)

    ulid = (
      if @prev.milliseconds < milliseconds
        ULID.generate(moment: milliseconds)
      else
        ULID.from_milliseconds_and_entropy(milliseconds: @prev.milliseconds, entropy: @prev.entropy.succ)
      end
    )

    unless ulid > @prev
      base_message = "monotonicity broken from unexpected reasons # generated: #{ulid.inspect}, prev: #{@prev.inspect}"
      additional_information = (
        if Thread.list == [Thread.main]
          '# NOTE: looks single thread only exist'
        else
          '# NOTE: ran on multi threads, so this might from concurrency issue'
        end
      )

      raise UnexpectedError, base_message + additional_information
    end

    @prev = ulid
    ulid
  end
end
inspect() click to toggle source

@return [String]

# File lib/ulid/monotonic_generator.rb, line 21
def inspect
  "ULID::MonotonicGenerator(prev: #{@prev.inspect})"
end
Also aliased as: to_s
to_s()
Alias for: inspect