Brad Wilson - The .NET Guy

Technologist. Agile Evangelist. Poker Player. Amateur Neologist. Metalhead.

My Links

Post Categories

Article Categories

Archives

Blog Stats

Stuff

Creating a GUID from Ruby/Windows

I was surprised that there was no native GUID functionality in Ruby. There is a library that can be downloaded, but I like to limit my team's tool scripts to what's available by default with the Win32 one-click installer. I need to be able to generate GUIDs for a script I'm writing that auto-generates Visual Studio 2005 project files.

So I fired up MSDN help for UuidCreate, and wrote this little bit of Ruby instead:

require 'Win32API'

@uuid_create = Win32API.new('rpcrt4', 'UuidCreate', 'P', 'L')

def new_guid
  result = ' ' * 16
  @uuid_create.call(result)
  a, b, c, d, e, f, g, h = result.unpack('SSSSSSSS')
  sprintf('{%04X%04X-%04X-%04X-%04X-%04X%04X%04X}', a, b, c, d, e, f, g, h)
end

The Win32API wrapper in Ruby is very simplistic, so translating the call was also pretty easy. It expects a pointer to a UUID structure, which will be filled out. The UUID structure is 16 bytes long, so we pre-allocate a string with 16 spaces and pass it that. Then the unpack method on the string is used to convert each 16-bit number into a Ruby Fixednum. Finally, sprintf provides me with the Microsoft-style formatted GUID in string form.

Wrapping it all up in a Guid class is left as an exercise for the reader. :)

posted on Thursday, October 27, 2005 6:46 AM