我正在通过迈克尔哈特尔的教程,但发现用户类变得有点混乱。我希望通过将大块功能分成单独的mixin来清理它(使用new-ish ActiveSupport::Concern
和旧self.included(klass)
模式)。
我在会话部分遇到了一些麻烦。
来自'models / user / 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
实例方法试图访问encrypt
和new_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)>
我觉得我错过了一些明显的东西。任何见解将不胜感激。提前谢谢!
答案 0 :(得分:6)
这两个方法是类方法,您在实例上调用它们。尝试:
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