Class: BareTest::UID

Inherits:
Object
  • Object
show all
Defined in:
lib/baretest/uid.rb

Overview

Generate a unique ID. Not using uuid simply to avoid two dependencies (uuid, and uuid’s dependency ‘macaddr’).

Constant Summary collapse

Epoch =

:nodoc:

Time.utc(2000,1,1).to_i

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeUID

Create a 128bit (16 Byte) long random number



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/baretest/uid.rb', line 28

def initialize
  now = Time.now
  
  # Works for the next 100 years - should be enough
  # after that, it'll wrap around.
  time_part_52   = (((now.to_i-Epoch) & 0xffffffff) << 20) + now.usec

  # Not solid, but for the purposes, should work
  process_part32 = (Thread.current.object_id ^ Process.pid) & 0xfffffffff

  # Add a bit of random noise
  random_part44  = Kernel.rand(0x100000000000)

  @value = (random_part44 << 84) + (process_part32 << 52) + time_part_52
end

Instance Attribute Details

#valueObject (readonly)

The numeric value of the uid (an Integer)



19
20
21
# File 'lib/baretest/uid.rb', line 19

def value
  @value
end

Class Method Details

.hex_uidObject

Returns a 32byte long String containing a new 16 byte random value in hex representation



23
24
25
# File 'lib/baretest/uid.rb', line 23

def self.hex_uid
  new.hex
end

Instance Method Details

#hexObject

Returns a 32byte long String containing the 16 byte random value in hex representation



46
47
48
# File 'lib/baretest/uid.rb', line 46

def hex
  "%032x" % @value
end