Method: Keybox::UUID#initialize

Defined in:
lib/keybox/uuid.rb

#initialize(bytes = nil) ⇒ UUID

the UUID can be initialized with:

- nothing ( default case ) in this case the UUID is generated
- a string in the standarde uuid format, in this case it is
  decoded and converted to the internal format
- a string of bytes, in this case they are considered to be
  the bytes used internally so 16 of them are taken


23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/keybox/uuid.rb', line 23

def initialize(bytes = nil)

    if bytes.nil? then
        @bytes = Keybox::RandomDevice.random_bytes(16)
    elsif bytes.size == 36 and bytes.split("-").size == 5 then
        if bytes =~ REGEX then
            # remove the dashes and make sure that we're all
            # lowercase
            b = bytes.gsub(/-/,'').downcase

            # convert to an array of hex strings
            b = b.unpack("a2"*16)

            # convert the hex strings to integers
            b.collect! { |x| x.to_i(16) }

            # and pack those integers into a string
            @bytes = b.pack("C*")

            # of course this could all be done in one line with
            # @bytes = bytes.gsub(/-/,'').downcase.unpack("a2"*16").collect {|x| x.to_i(16) }.pack("C*")
        else
            raise ArgumentError, "[#{bytes}] is not a hex encoded UUID"
        end
    elsif bytes.kind_of?(String) and bytes.length >= 16
        @bytes = bytes[0..16]
    else
        raise ArgumentError, "[#{bytes}] cannot be converted to a UUID"
    end
end