输出前的哈希值

时间:2013-03-04 12:17:46

标签: ruby-on-rails ruby

我希望在从Rails模型输出之前,MD5哈希一个电子邮件地址。目前我的模态看起来像这样:

class Comment < ActiveRecord::Base
    belongs_to :post
    attr_accessible :body, :name, :reply, :email
    validates_presence_of :body, :name

    def gravator
        require 'digest/md5'

        email_address = self.email.downcase

        # create the md5 hash
        hash = Digest::MD5.hexdigest(email_address)

        # compile URL which can be used in <img src="RIGHT_HERE"...
        self.email = "http://www.gravatar.com/avatar/#{hash}"

    end
end

我想知道将电子邮件字段转换为gravator方法输出的URL的最佳方法是什么。

感谢您的帮助!

2 个答案:

答案 0 :(得分:0)

不是每次都对它进行散列,而是在数据库中创建一个包含散列值的新字段。

答案 1 :(得分:0)

创建gravator字段并在before_save上分配。这样可以加快速度,每次显示时都不会调用数据库。

class Comment < ActiveRecord::Base
    belongs_to :post
    attr_accessible :body, :name, :reply, :email
    validates_presence_of :body, :name
    before_save :set_gravator

    def set_gravator
        require 'digest/md5'

        email_address = self.email.downcase

        # create the md5 hash
        hash = Digest::MD5.hexdigest(email_address)

        # compile URL which can be used in <img src="RIGHT_HERE"...
        self.gravator = "http://www.gravatar.com/avatar/#{hash}"
    end
end