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


339
340
341
342
343
# File 'lib/bson/object_id.rb', line 339

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


330
331
332
# File 'lib/bson/object_id.rb', line 330

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


377
378
379
# File 'lib/bson/object_id.rb', line 377

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


356
357
358
359
360
361
362
363
364
# File 'lib/bson/object_id.rb', line 356

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