2012-03-16 28 views
1

我有一個模塊A,並且有幾個類需要Mixin它,還有一個方法應該寫爲該模塊的Class Method,但是這種方法需要從與這些類匹配的表中獲取數據。它可以實現嗎?在模塊類方法中,是否有可能獲得在該模塊中混合的類?

module Authenticate 
    def password=(password) 
    if password.present? 
     generate_salt 
     self.hashed_password = Authenticate.encrypt_password(password, salt) 
    end 
    end 

    class << self 
    def encrypt_password(password,salt) 
     Digest::SHA2.hexdigest(password + salt) 
    end 
    end 

    private 
    def generate_salt 
    self.salt = self.object_id.to_s + rand.to_s 
    end 

end 


require 'authenticate_module' 
class Administrator < ActiveRecord::Base 
    validates :password, :confirmation => true 
    attr_accessor :password_confirmation 
    attr_reader :password 
    include Authenticate 
end 

這是一個方法:

def authenticate(name,password) 
    if user = ???.find_by_name(name) 
    if user.hashed_password == Authenticate.encrypt_password(password,user.salt) 
     user 
    end 
    end 
end 
+2

評論,因爲我不知道這是正確的..你有沒有嘗試過'self.class'你的'???'是什麼? – noodl 2012-03-16 16:12:09

+0

我認爲這可能在實例方法中起作用,類方法中的「放置自己」將會是「Authenticate」。 – 2012-03-17 00:06:10

回答

1

請使用ActiveSupport ::關注類方法添加到每一個包括你的模塊,然後調用該方法將返回類名稱自我類。

這將是這樣的:

module Authenticate 
    extend ActiveSupport::Concern 

    module ClassMethods 
    def authenticate(name, password) 
     self.class # returns the name of the class that includes this module 
    end 
    end 
end 


class User 
    include Authenticate 
end 


# Now You can call 
User.authenticate(name, password) 

不會有什麼的ActiveSupport ::值得關注的是,每當一類包括模塊,它擴展與ClassMethods階級在這裏是相當於做

class User 
    include Authenticate 
    extend Authenticate::ClassMethods 
end 
+0

對不起,不回答這些天,感謝〜 – 2012-03-21 02:30:46

+0

我不相信你必須包括這種說法 擴展身份驗證:: ClassMethods 作爲的ActiveSupport ::關注已經這樣做了你! – bokor 2012-04-01 20:23:05

+0

@designwaves我只是解釋說,使用ActiveSupport :: Concern等同於這兩個命令。這不是解決方案的一部分。 – Dipil 2012-04-03 05:40:24

相關問題