class Torid::Generator

A class that will generate unique identifiers.

Torid::Generator is the class that is used to generate Torid::UUID instances.

Example:

Torid::Generator.next # => Torid::UUID

generator = Torid::Generator.new
generator.next                    # => Torid::UUID

Public

↑ top

Public Class Methods

next() click to toggle source

Return the next UUID from the default Generator

Returns

Returns a Torid::UUID

# File lib/torid/generator.rb, line 94
def self.next
  @instance.next
end
node_id() click to toggle source

Return the node id of the default Generator instance

Returns

Returns a 64 bit Integer

# File lib/torid/generator.rb, line 87
def self.node_id
  @instance.node_id
end

Public Instance Methods

next() click to toggle source

Return the next UUID from this generator

Returns

Returns Torid::UUID

# File lib/torid/generator.rb, line 39
def next
 Torid::UUID.new( clock.tick, node_id )
end
node_id() click to toggle source

Return the node id

This also checks if the node id is still a valid node id, by checking the pid of the process and the pid of the last time the node id was generated.

Returns

Returns the node_id

# File lib/torid/generator.rb, line 50
def node_id
  current_pid = Process.pid
  if current_pid != @pid then
    @pid     = current_pid
    @node_id = Generator.create_node_id( @pid )
  end
  return @node_id
end

Internal

↑ top

Attributes

clock[R]

The Clock instance used to get 64bit timestamps

Public Class Methods

create_node_id( pid = Process.pid ) click to toggle source

Generate a unique node identifier.

Uses the first hostname of the system, the process id, some random bytes and hashes them all together using the non-cryptographic FNV hash.

en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function

This method is copeid from github.com/jamesgolick/lexical_uuid/blob/master/lib/lexical_uuid.rb#L14 with the random bytes added by me.

Settled on using just `Socket.gethostname` because on MacOS Sierra the hostname is not guaranteed to be round tripable through name resolution locally on the machine

Returns

Returns a 64 bit Integer

# File lib/torid/generator.rb, line 75
def self.create_node_id( pid = Process.pid )
  hostname = Socket.gethostname
  random   = SecureRandom.hex( 16 )
  FNV.new.fnv1a_64("#{hostname}-#{pid}-#{random}")
end
new( clock = Torid::Clock, node_id = Generator.create_node_id ) click to toggle source

Create a new Torid UUID Generator

clock

an object that responds to `#tick` and returns a 64bit integer. (default: Torid::Clock)

node_id

the 64bit node id of this node. (default: Generator.create_node_id)

# File lib/torid/generator.rb, line 30
def initialize( clock = Torid::Clock, node_id = Generator.create_node_id )
  @clock   = clock
  @node_id = node_id
  @pid     = Process.pid
end