1

アクティブなレコード クラスに含まれるモジュールのインスタンス メソッド内からクラス メソッドを呼び出す方法に興味があります。たとえば、ユーザー モデルとクライアント モデルの両方で、パスワード暗号化の基本を共有したいと考えています。

# 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 の検索に失敗します

何かご意見は?

4

1 に答える 1

1

クラスメソッドのように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 
于 2010-03-27T07:32:35.967 に答える