This post originated from an RSS feed registered with .NET Buzz
by Brad Wilson.
Original Post: Creating a GUID from Ruby/Windows
Feed Title: The .NET Guy
Feed URL: /error.aspx?aspxerrorpath=/dotnetguy/Rss.aspx
Feed Description: A personal blog about technology in general, .NET in specific, and when all else fails, the real world.
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. :)