4

我正在阅读 Michael Hartl 的教程,但发现 User 类有点混乱。我想通过将大块功能拉入单独的 mixin 来稍微清理一下(使用 new-ish ActiveSupport::Concern,而不是旧self.included(klass)模式)。

我在“会话”部分遇到了一些麻烦。

从“模型/用户/session_management.rb”:

require 'active_support/concern'

module SessionManagement
  extend ActiveSupport::Concern

  included do
    before_create :create_remember_token
  end

  private
      def create_remember_token
        self.remember_token = self.encrypt(self.new_remember_token)
      end

  module ClassMethods
   def new_remember_token
      SecureRandom.urlsafe_base64
    end

    def encrypt(token)
      Digest::SHA1.hexdigest(token.to_s)
    end
  end
end

我包含在“models/user.rb”中:

require 'user/authentication'
require 'user/session_management'

class User < ActiveRecord::Base
  ...

  include Authentication
  include SessionManagement

  ...

end

这适用于身份验证模块(实际上只是验证和has_secure_password)。但是,create_remember_token实例方法正在尝试访问encryptnew_remember_token类方法。

NoMethodError:
  undefined method `new_remember_token' for #<User:0x007f8e17e338f0>
  # ./app/models/user/session_management.rb:13:in 'create_remember_token'
  # ./spec/models/user_spec.rb:152:in `block (4 levels) in <top (required)>

我觉得我错过了一些明显的东西。任何见解将不胜感激。提前致谢!

4

1 回答 1

7

这两个方法是类方法,您在实例上调用它们。尝试:

def create_remember_token
  self.remember_token = self.class.encrypt(self.class.new_remember_token)
end

或(首选)将它们移出ClassMethods模块。

require 'active_support/concern'

module SessionManagement
  extend ActiveSupport::Concern

  included do
    before_create :create_remember_token
  end

  private
    def create_remember_token
      self.remember_token = encrypt(new_remember_token)
    end

    def new_remember_token
      SecureRandom.urlsafe_base64
    end

   def encrypt(token)
     Digest::SHA1.hexdigest(token.to_s)
   end

end
于 2014-01-08T18:40:05.480 回答