2012-07-16 32 views
1

我在學習SOLID並試圖將SRP引入到我的Rails應用程序中。我有一個基本的身份驗證以下用戶模型:Rails SRP模塊,attr_accessible

class User < ActiveRecord::Base 
    attr_accessible :password, :password_confirmation 
    attr_accessor :password 

    before_save :encrypt_password 

    validates_confirmation_of :password 
    validates_presence_of  :password, :on => :create 

    def self.authenticate(email, password) 
    user = find_by_email(email) 
    if user && user.password_hash == BCrypt::Engine.hash_secret(password, user.password_salt) 
     user 
    else 
     nil 
    end 
    end 

    def encrypt_password 
    if password.present? 
     self.password_salt = BCrypt::Engine.generate_salt 
     self.password_hash = BCrypt::Engine.hash_secret(password, password_salt) 
    end 
    end 

    def self.generate_random_password 
    return ActiveSupport::SecureRandom.hex(12) 
    end 
end 

我想所有的驗證邏輯移至模塊,像這樣:

module Authentication 

    attr_accessible :password, :password_confirmation 
    attr_accessor :password 

    before_save :encrypt_password 

    validates_confirmation_of :password 
    validates_presence_of  :password, :on => :create 

    def self.authenticate(email, password) 
    user = find_by_email(email) 
    if user && user.password_hash == BCrypt::Engine.hash_secret(password, user.password_salt) 
     user 
    else 
     nil 
    end 
    end 

    def encrypt_password 
    if password.present? 
     self.password_salt = BCrypt::Engine.generate_salt 
     self.password_hash = BCrypt::Engine.hash_secret(password, password_salt) 
    end 
    end 

    def self.generate_random_password 
    return ActiveSupport::SecureRandom.hex(12) 
    end 
end 

而且我的用戶模型應該是這樣的:

class User < ActiveRecord::Base 
    include Authentication #SRP in action! :P 
end 

而現在的錯誤開始:

未定義的方法`attr_accessible'進行身份驗證:模塊

我該如何解決此錯誤?我確信這是將SRP引入到我的Rails應用程序的最佳開始。

謝謝

回答

2

attr_accessible方法在錯誤的範圍內調用。看看關注解決這個問題:

http://api.rubyonrails.org/classes/ActiveSupport/Concern.html

這將導致:

module Authentication 
    extend ActiveSupport::Concern 
    included do 
    attr_accessible :password, :password_confirmation 
    end 
    ... 
end 

這也將照顧你類和實例方法定義。

注意:具體而言,這並不完全實現SRP,因爲即使將多個職責分離爲多個模塊,多個職責仍然在同一個類中共享。通過引用或裝飾構成課堂是一個更嚴格的解決方案,但我更喜歡模塊的實用方法。