2010-03-25 70 views
1

好奇如何从一个活动记录类包含的模块的实例方法中调用一个类方法。例如,我希望用户和客户端模型共享密码加密的细节和螺栓。从模块的实例方法中调用一个类方法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( '密码')未能查找方法用户#ENCRYPT_PASSWORD

有什么想法?

回答

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 
相关问题