class Snowflakes::Node

Constants

MAX_NODES
MAX_STEPS
NODE_BITS
STEP_BITS

Public Class Methods

new(id, step = 0, since = 0) click to toggle source
# File lib/snowflakes.rb, line 42
def initialize(id, step = 0, since = 0)
  if not id.is_a? Integer or id < 0 or id >= MAX_NODES
    raise OverflowError.new('id', id, MAX_NODES)
  end

  if not step.is_a? Integer or step < 0 or step >= MAX_STEPS
    raise OverflowError.new('step', step, MAX_STEPS)
  end

  @id = id
  @last = 0
  @step = step
  @since = since
end

Public Instance Methods

next() click to toggle source
# File lib/snowflakes.rb, line 57
def next
  time = now

  if time < @last
    raise InvalidSystemClockError.new(time, @last)
  end

  if time == @last
    @step = (@step + 1) % MAX_STEPS
    if @step == 0
      time = waitUntilNextMillisecond(time)
    end
  else
    @step = 0
  end

  @last = time

  generate(time, @id, @step)
end
now() click to toggle source
# File lib/snowflakes.rb, line 78
def now
  (Time.now.to_f * 1000).to_i - @since
end
parse() click to toggle source
# File lib/snowflakes.rb, line 82
def parse
end

Private Instance Methods

generate(time, id, step) click to toggle source
# File lib/snowflakes.rb, line 87
def generate(time, id, step)
  Snowflake.new(time, id << (STEP_BITS) + step)
end
waitUntilNextMillisecond(time) click to toggle source
# File lib/snowflakes.rb, line 91
def waitUntilNextMillisecond(time)
  t = time
  while t < time
    t = now
  end
  t
end