Friday, 4 September 2009

UUID over the wire

Need to use Active Resource on a remote object that has a UUID?

Last time I checked, Active Resource still overwrites the id with a to_i version of the uuid... this makes "123ABCDE456" turn into 123... not what we want.

But Hyperactive Resource (HyRes) works just fine.

UUID created by the remote system

Does the remote API create the UUID for you? If so - you're laughing. Just add: self.primary_key = :uuid to your HyRes object and you're set. HyRes doesn't do a to_i conversion, so the UUID will still be stored as a string.

Need to set UUID locally?

Install the 'uuidtools' gem then add a before_create callback (in your resource) thus:

# for uuid-generation
require 'uuidtools'
class Widget < HyperactiveResource = 'http://localhost:3001' # etc...
  self.columns = [:uuid, :widget_type, :name, :description] # etc...

  self.primary_key = :uuid
  before_create :generate_uuid

  # helper to generate a uuid for each asset
  def generate_uuid
    self.uuid = UUIDTools::UUID.timestamp_create.to_s