从模块 mixin (rails) 的实例方法内部调用类方法
好奇如何从活动记录类包含的模块的实例方法内部调用类方法。例如,我希望用户和客户端模型共享密码加密的具体细节。
# 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
有什么想法吗?
Curious how one would go about calling a class method from inside an instance method of a module which is included by an active record class. For example I want both user and client models to share the nuts and bolts of password encryption.
# 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
However, this fails. Says that the class method cannot be found when the instance method calls it. I can call
User.encrypt_password('password')
but
User.authenticate('password') fails to look up the method User#encrypt_password
Any thoughts?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要像类方法一样的 encrypt_password
You need the encrypt_password like a class method