Class: Couchbase::Model::UUID

Inherits:
Object
  • Object
show all
Defined in:
lib/couchbase/model/uuid.rb

Overview

Generator of CouchDB specfic UUIDs. This is the ruby implementation of couch_uuids.erl from couchdb distribution. It is threadsafe.

Since:

  • 0.0.1

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(seed = nil) ⇒ UUID

Initialize generator.

Since:

  • 0.0.1



44
45
46
47
48
49
# File 'lib/couchbase/model/uuid.rb', line 44

def initialize(seed = nil)
  seed ? srand(seed) : srand
  @prefix, _ = rand_bytes(13).unpack('H26')
  @inc = rand(0xfff) + 1
  @lock = Mutex.new
end

Class Method Details

.generatorUUID

Get default UUID generator. You can create your own if you like.

Since:

  • 0.0.1



35
36
37
# File 'lib/couchbase/model/uuid.rb', line 35

def self.generator
  @generator ||= UUID.new
end

Instance Method Details

#next(count = 1, algorithm = :sequential) ⇒ String, Array

Generate list of UUIDs.

Raises:

  • (ArgumentError)

Since:

  • 0.0.1



71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# File 'lib/couchbase/model/uuid.rb', line 71

def next(count = 1, algorithm = :sequential)
  raise ArgumentError, 'count should be a positive number' unless count > 0
  uuids = case algorithm
          when :random
            rand_bytes(16 * count).unpack('H32' * count)
          when :utc_random
            now = Time.now.utc
            prefix = '%014x' % [now.to_i * 1_000_000 + now.usec]
            rand_bytes(9 * count).unpack('H18' * count).map do |tail|
              "#{prefix}#{tail}"
            end
          when :sequential
            (1..count).map{ next_seq }
          else
            raise ArgumentError, "Unknown algorithm #{algo}. Should be one :sequential, :random or :utc_random"
          end
  uuids.size == 1 ? uuids[0] : uuids
end