从模块mixin(rails)中调用实例方法中的类方法

时间:2010-03-25 18:20:14

标签: ruby-on-rails module mixins

好奇如何从一个活动记录类包含的模块的实例方法中调用类方法。例如,我希望用户和客户端模型共享密码加密的细节。

# app/models
class User < ActiveRecord::Base
  include Encrypt
end
class Client < ActiveRecord::Base
  include Encrypt
end

# app/models/shared/encrypt.rb
module Encrypt
  def authenticate
    # I want to call the ClassMethods#encrypt_password method when @user.authenticate is run 
    self.password_crypted == self.encrypt_password(self.password) 
  end
  def self.included(base)
    base.extend ClassMethods
  end  
  module ClassMethods
    def encrypt_password(password)
     Digest::SHA1.hexdigest(password)
    end
  end
end  

然而,这失败了。说实例方法调用它时找不到类方法。我可以打电话 User.encrypt_password( '密码') 但 User.authenticate('password')无法查找User#encrypt_password

方法

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

你需要像类方法一样加密密码

module Encrypt
  def authenticate
    # I want to call the ClassMethods#encrypt_password method when @user.authenticate is run 
    self.password_crypted == self.class.encrypt_password(self.password) 
  end
  def self.included(base)
    base.extend ClassMethods
  end  
  module ClassMethods
    def encrypt_password(password)
     Digest::SHA1.hexdigest(password)
    end
  end
end