簡體   English   中英

從模塊mixin(rails)的實例方法內部調用類方法

[英]call a class method from inside an instance method from a module 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('password'),但User.authenticate('password')無法查找方法User#encrypt_password

有什么想法嗎?

您需要像類方法一樣的crypto_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 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM