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

发布于 2024-08-26 23:30:18 字数 772 浏览 9 评论 0原文

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

# 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

丶视觉 2024-09-02 23:30:18

您需要像类方法一样的 encrypt_password

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 

You need the encrypt_password like a class method

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 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文