我正在学习扎实,并试图将SRP引入我的rails应用程序中。我有以下具有基本身份验证的用户模型:
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应用程序的最好开始。
谢谢
发布于 2012-07-16 08:24:30
在错误的范围内调用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,因为多个责任仍然在同一个类中共享,即使它们被分离成模块。通过引用或修饰的类组成将是一个更严格的解决方案,但我更喜欢模块的实用方法。
https://stackoverflow.com/questions/11499556
复制相似问题