Ruby on rails自定義setter與getter

最近須要搭幾個臨時的api做爲移動客戶端測試用,一時手癢想嘗試一下ROR,結果卡在了存儲密碼的環節。由於不想在數據庫裏存明文,因此將它們先作了一個MD5。這就須要自定義password屬性的setter,一開始在《Web敏捷開發之道》上找到@password來方法實例變量的方式,可是每次取到的結果都是nil。只好找了一下api文檔,發現寫法以下:數據庫

 1 class Song < ActiveRecord::Base
 2   # Uses an integer of seconds to hold the length of the song
 3 
 4   def length=(minutes)
 5     write_attribute(:length, minutes.to_i * 60)
 6   end
 7 
 8   def length
 9     read_attribute(:length) / 60
10   end
11 end

固然,還有另一種推薦寫法:api

self[:attribute]=(value) 和 self[:attribute]測試

相關文章
相關標籤/搜索