首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Rails SRP模块,attr_accessible

Rails SRP模块,attr_accessible
EN

Stack Overflow用户
提问于 2012-07-16 07:05:54
回答 1查看 893关注 0票数 1

我正在学习扎实,并试图将SRP引入我的rails应用程序中。我有以下具有基本身份验证的用户模型:

代码语言:javascript
复制
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

我希望将所有身份验证逻辑移到如下所示的模块:

代码语言:javascript
复制
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

我的用户模型是这样的:

代码语言:javascript
复制
class User < ActiveRecord::Base
  include Authentication #SRP in action! :P
end

现在,错误开始了:

用于身份验证的未定义方法`attr_accessible‘:模块

我如何纠正这个错误?我相信这是把SRP引入我的Rails应用程序的最好开始。

谢谢

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-07-16 08:24:30

在错误的范围内调用attr_accessible方法。请看一下修复这个问题的关注点:

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

这将导致:

代码语言:javascript
复制
module Authentication
  extend ActiveSupport::Concern
  included do
    attr_accessible :password, :password_confirmation
  end
  ...
end

这还将处理类和实例方法定义。

注意:具体来说,这并不能完全实现SRP,因为多个责任仍然在同一个类中共享,即使它们被分离成模块。通过引用或修饰的类组成将是一个更严格的解决方案,但我更喜欢模块的实用方法。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11499556

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档