Class: LexicalUUID

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

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(timestamp = nil, worker_id = nil, timestamp_factory = IncreasingMicrosecondClock) ⇒ LexicalUUID

Returns a new instance of LexicalUUID.



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/lexical_uuid.rb', line 23

def initialize(timestamp = nil, worker_id = nil, timestamp_factory = IncreasingMicrosecondClock)
  case timestamp
  when Fixnum, Bignum
    @timestamp = timestamp
    @worker_id = worker_id || self.class.worker_id
  when String
    case timestamp.size
    when 16
      from_bytes(timestamp)
    when 36
      elements = timestamp.split("-")
      from_bytes(Array(elements.join).pack('H32'))
    else
      raise ArgumentError, 
        "#{timestamp} was incorrectly sized. Must be 16 timestamp."
    end
  when Time
    @timestamp = timestamp.stamp
    @worker_id = self.class.worker_id
  when nil
    @worker_id = self.class.worker_id
    @timestamp = timestamp_factory.call
  end
end

Instance Attribute Details

#timestampObject (readonly)

Returns the value of attribute timestamp.



21
22
23
# File 'lib/lexical_uuid.rb', line 21

def timestamp
  @timestamp
end

#worker_idObject (readonly)

Returns the value of attribute worker_id.



21
22
23
# File 'lib/lexical_uuid.rb', line 21

def worker_id
  @worker_id
end

Class Method Details

.worker_idObject



9
10
11
# File 'lib/lexical_uuid.rb', line 9

def worker_id
  @worker_id ||= create_worker_id
end

Instance Method Details

#<=>(other) ⇒ Object



63
64
65
66
# File 'lib/lexical_uuid.rb', line 63

def <=>(other)
  timestamp == other.timestamp ? 
    worker_id <=> other.worker_id : timestamp <=> other.timestamp
end

#==(other) ⇒ Object



68
69
70
71
72
# File 'lib/lexical_uuid.rb', line 68

def ==(other)
  other.is_a?(LexicalUUID) &&
    timestamp == other.timestamp &&
      worker_id == other.worker_id
end

#eql?(other) ⇒ Boolean

Returns:

  • (Boolean)


74
75
76
# File 'lib/lexical_uuid.rb', line 74

def eql?(other)
  self == other
end

#hashObject



78
79
80
# File 'lib/lexical_uuid.rb', line 78

def hash
  to_bytes.hash
end

#to_bytesObject



48
49
50
51
52
53
# File 'lib/lexical_uuid.rb', line 48

def to_bytes
  [timestamp >> 32,
    timestamp & 0xffffffff,
    worker_id >> 32,
    worker_id & 0xffffffff].pack("NNNN")
end

#to_guidObject

Also borrowed from simple_uuid



56
57
58
59
60
61
# File 'lib/lexical_uuid.rb', line 56

def to_guid
  elements     = to_bytes.unpack("NnnCCa6")
  node         = elements[-1].unpack('C*')
  elements[-1] = '%02x%02x%02x%02x%02x%02x' % node
  "%08x-%04x-%04x-%02x%02x-%s" % elements
end