Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I transparently modify an ActiveRecord method in a model?

I have a model with UUIDs stored in BINARY(16) field in a MySQL table. I would like to be able to transparently convert hexadecimal uuid into binary for the setter method and back when I use the getter method.

what is the 'right' way to proceed?

like image 667
dimus Avatar asked Feb 08 '10 19:02

dimus


1 Answers

You override the setter and getter:

class User < ActiveRecord::Base
  def uuid=(value)
    @uuid = write_attribute(:uuid, value.scan(/../).map {|n| n.to_i(16)}.pack("C*"))
  end

  def uuid
    @uuid ||= read_attribute(:uuid).unpack("C*").map {|n| sprintf("%02x", n)}.join
  end
end

Of course, you'd want a BINARY column, because you're sending raw bytes to the DB. A migration such as this one:

class AddUuidToUsers
  def self.up
    execute "ALTER TABLE users ADD uuid BINARY(16)"
  end
end
like image 176
François Beausoleil Avatar answered Nov 01 '22 07:11

François Beausoleil