zoukankan      html  css  js  c++  java
  • 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]

  • 相关阅读:
    vmstat
    linux内存机制
    TOP命令
    linux下查阅文件内容cat,more,less,tail
    linux stat命令
    linux修改主机名-IP
    alias
    linux软硬链接
    linux 常用find命令
    ubuntu下交叉编译imagemagick
  • 原文地址:https://www.cnblogs.com/jsxh/p/3397710.html
Copyright © 2011-2022 走看看