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

当然,还有另外一种推荐写法:

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

原文地址:https://www.cnblogs.com/jsxh/p/3397710.html