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:

Class Method Summary (collapse)

Instance Method Summary (collapse)

Constructor Details

- (UUID) initialize(seed = nil)

Initialize generator.

Parameters:

  • seed (Fixnum) (defaults to: nil)

    seed for pseudorandom number 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

+ (UUID) generator

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

Returns:

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

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

Generate list of UUIDs.

Parameters:

  • count (Fixnum) (defaults to: 1)

    number of UUIDs you need

  • algorithm (Symbol) (defaults to: :sequential)

    Algorithm to use. Known algorithms:

    :random

    128 bits of random awesome. All awesome, all the time.

    :sequential

    Monotonically increasing ids with random increments. First 26 hex characters are random. Last 6 increment in random amounts until an overflow occurs. On overflow, the random prefix is regenerated and the process starts over.

    :utc_random

    Time since Jan 1, 1970 UTC with microseconds. First 14 characters are the time in hex. Last 18 are random.

Returns:

  • (String, Array)

    single string value or array of strings. Where each value represents 128-bit number written in hexadecimal format.

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