好奇如何从活动记录类包含的模块的实例方法内部调用类方法。例如,我希望用户模型和客户端模型共享密码加密的细节。
# 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('password') 但 User.authenticate('password') 无法查找方法 User#encrypt_password
有什么想法吗?