好奇如何从一个活动记录类包含的模块的实例方法中调用类方法。例如,我希望用户和客户端模型共享密码加密的细节。
# 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
方法有什么想法吗?
答案 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