Ruby on rails 3 Rails SRP模块,属性可访问
我正在学习SOLID并尝试将SRP引入我的rails应用程序。我有以下具有基本身份验证的用户模型:Ruby on rails 3 Rails SRP模块,属性可访问,ruby-on-rails-3,module,single-responsibility-principle,attr-accessible,Ruby On Rails 3,Module,Single Responsibility Principle,Attr Accessible,我正在学习SOLID并尝试将SRP引入我的rails应用程序。我有以下具有基本身份验证的用户模型: class User < ActiveRecord::Base attr_accessible :password, :password_confirmation attr_accessor :password before_save :encrypt_password validates_confirmation_of :password validates_pre
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
我的用户模型是这样的:
class User < ActiveRecord::Base
include Authentication #SRP in action! :P
end
class用户
现在错误开始了:
用于身份验证的未定义方法“attr\u accessible”:模块
如何修复此错误?我相信这是将SRP引入我的Rails应用程序的最佳开端
谢谢属性可访问方法在错误的范围内调用。请查看解决此问题的关注点: 这将导致:
module Authentication
extend ActiveSupport::Concern
included do
attr_accessible :password, :password_confirmation
end
...
end
这还将处理类和实例方法定义
注意:具体来说,这并不能完全实现SRP,因为在同一个类中仍然共享多个职责,即使它们被分成模块。通过引用或装饰来组合类将是一个更严格的解决方案,但我更喜欢模块的实用方法
module Authentication
extend ActiveSupport::Concern
included do
attr_accessible :password, :password_confirmation
end
...
end