I’m currently working on a Rails project where I need to generate GUID’s which is often used when you want the ability to offer portable data which is associated with a particular user or account.
First I thougth about the “traditional” approach where you encrypt Time.new or something like that to generate something uniq. But since mysql can create unique id’s for you, why not use that option instead?
Try to run this query against you mysql database: SELECT uuid() as uuid; It will return a unique string for you, it is defined as “A UUID is designed as a number that is globally unique in space and time” which serves just perfect for this purpose.
To be able to handle this using Rails you need to generate custom SQL which is done using “ActionRecord::Base.connection.execute(sql statement)”. I like my ruby code to be short and if possible oneliners… I know I know, oneliners are the worst when it comes to debugging and to many difficult to read as well, but hey, I’m an old Perl hacker so what can I do :)
This is what I ended up with as a first hack:
class Provider < ActiveRecord::Base
has_many :events
has_many :locationsbefore_create :generate_pubkey
private
def generate_pubkey
self.pubkey = ActiveRecord::Base.connection.execute(“SELECT uuid() AS uuid”).fetch_row.first
end
end
Just before a new provider is stored in the database, a pubkey value is assigned to that entry.
Brilliant! I love it.
To bad it’s MySQL only, but that’s pretty much all I use anyway.
Yes, I mostly use mysql but you can use http://raa.ruby-lang.org/project/ruby-guid/ instead, I haven’t tested it.