Class: BSON::ObjectId::Generator Private

Inherits:
Object
  • Object
show all
Defined in:
lib/bson/object_id.rb

Overview

This class is part of a private API. You should avoid using this class if possible, as it may be removed or be changed in the future.

Inner class that encapsulates the behaviour of actually generating each part of the ObjectId.

Since:

  • 2.0.0

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeGenerator

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Instantiate the new object id generator. Will set the machine id once on the initial instantiation.

Examples:

Instantiate the generator.

BSON::ObjectId::Generator.new

Since:

  • 2.0.0



333
334
335
336
337
# File 'lib/bson/object_id.rb', line 333

def initialize
  @counter = rand(0x1000000)
  @machine_id = Digest::MD5.digest(Socket.gethostname).unpack("N")[0]
  @mutex = Mutex.new
end

Instance Attribute Details

#machine_idObject

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Since:

  • 2.0.0



324
325
326
# File 'lib/bson/object_id.rb', line 324

def machine_id
  @machine_id
end

Instance Method Details

#generate(time, counter = 0) ⇒ String

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Generate object id data for a given time using the provided counter.

Examples:

Generate the object id bytes.

generator.generate(time)

Parameters:

  • time (Integer)

    The time since epoch in seconds.

  • counter (Integer) (defaults to: 0)

    The optional counter.

Returns:

  • (String)

    The raw object id bytes.

Since:

  • 2.0.0



371
372
373
# File 'lib/bson/object_id.rb', line 371

def generate(time, counter = 0)
  [ time, machine_id, process_id, counter << 8 ].pack("N NX lXX NX")
end

#next_object_id(time = nil) ⇒ String

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Return object id data based on the current time, incrementing the object id counter. Will use the provided time if not nil.

Examples:

Get the next object id data.

generator.next_object_id

Parameters:

  • time (Time) (defaults to: nil)

    The optional time to generate with.

Returns:

  • (String)

    The raw object id bytes.

Since:

  • 2.0.0



350
351
352
353
354
355
356
357
358
# File 'lib/bson/object_id.rb', line 350

def next_object_id(time = nil)
  @mutex.lock
  begin
    count = @counter = (@counter + 1) % 0xFFFFFF
  ensure
    @mutex.unlock rescue nil
  end
  generate(time || ::Time.new.to_i, count)
end