在model或class中建立uid(unique identifier)
如果你希望能在model中建立新資料的時候能自動生出一個uid,但這個uid必須是read-only,而且有presence與uniqueness的vaildation,那麼這個gem就是在做這件事。
class AddUidToMyModels < ActiveRecord::Migration
def change
add_column :my_models, :uid, :string, null: false
add_index :my_models, :uid, unique: true
end
end
class MyModel
include Uidable
uidable
end
a = MyClass.new
a.uid # nil
a.save
a.uid "cmerft8rotdy7wvmtxc63ljoxos67bc8"
class MyClass
include Uidable
uidable uid_size: 64, read_only: false
end
a = MyClass.new
a.uid # "zcf45ltmkyh4w2ofsc1rp8dka6wi4flt3h3szwo1z4rkfsvk387mclg1cikutbc7"
這個gem還提供了一些選項可以做調整,例如更新uid的欄位名稱,或是讓to_param
回傳uid而非id,詳細的使用方式可以參考它的測試檔案。
從很早之前,我就已經在我的project中使用了uidable,只是它是一個自己寫的concern,最近才決定把它寫成一個gem。不過因為之前都沒有寫過用在ActiveRecord的gem,所以參考了enumerize與sunspot的程式碼,發現裡面用了超多的meta-programming的技巧,再加上module的include與extend,真的讓我功力大增啊。