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]测试

相关文章
相关标签/搜索