attr_uuid
attr_uuid makes binary uuid attribute easy to use.
Installation
Add this line to your application's Gemfile:
gem 'attr_uuid'
And then execute:
$ bundle
Or install it yourself as:
$ gem install attr_uuid
Usage
In a migration file, prevent generate id column and add uuid column (tinyblob).
class CreateUsers < ActiveRecord::Migration def up create_table :users, :id => false do |t| t.column :uuid, :tinyblob t.string :user_name end execute "ALTER TABLE users ADD PRIMARY KEY (`uuid`(16))" end def down drop_table :users end endChange primary_key to uuid, and call
attr_uuidmethod in a model class. When you passautofill: truetoattr_uuid, it hooksbefore_createcallback to set automatically generated uuid as 16 byte binary data to id attirbute.class User < ActiveRecord::Base self.primary_key = "uuid" attr_uuid :id, column_name: "uuid", autofill: true endattr_uuidadds#hex_id,#hex_id=,#formatted_idand#formatted_id=to the model to refer formatted uuid.user = User.create(:user_name => "foo") user.id #=> "3~\x05v\xCBfAQ\xA2\xE1\xE0\xFC\x04\xFB3\xD1" user.hex_id #=> "337e0576cb664151a2e1e0fc04fb33d1" user.formatted_id #=> "337e0576-cb66-4151-a2e1-e0fc04fb33d1" user.hex_id = "9f648b40fa6e11e3a3ac0800200c9a66" user.id #=> "\x9Fd\x8B@\xFAn\x11\xE3\xA3\xAC\b\x00 \f\x9Af" user.formatted_id #=> "9f648b40-fa6e-11e3-a3ac-0800200c9a66"attr_uuidalso adds.find_by_hex_id,.find_by_formatted_id,.find_all_by_hex_idand.find_all_by_formatted_idmethods to retrive model from data store with an uuid string.User.find_by_hex_id("337e0576cb664151a2e1e0fc04fb33d1") User.find_by_formatted_id("337e0576-cb66-4151-a2e1-e0fc04fb33d1") User.find_all_by_hex_id(["337e0576cb664151a2e1e0fc04fb33d1", "5a038fcdfcd644b5bffa0245c7cfd7fa", "165a33cff2a947549d960d95adfd119a"]) User.find_all_by_formatted_id(["337e0576-cb66-4151-a2e1-e0fc04fb33d1", "5a038fcd-fcd6-44b5-bffa-0245c7cfd7fa", "165a33cf-f2a9-4754-9d96-0d95adfd119a"])
Contributing
- Fork it
- Create your feature branch (
git checkout -b my-new-feature) - Commit your changes (
git commit -am 'Add some feature') - Push to the branch (
git push origin my-new-feature) - Create new Pull Request