[英]How do I include a gem's class method in a Rails model?
I'm learning how to write a gem. 我正在学习如何编写宝石。 I want to add some methods that I will use in a User model in Rails.
我想添加一些将在Rails的User模型中使用的方法。
# app/models/user.rb
class User
include Mongoid::Document
include Authme::Model # here's my gem.
field :password_digest, type: String
end
# Gemfile
gem 'authme'
Now, inside my gem I have the following: 现在,在我的宝石中,我有以下内容:
- authme
- lib
+ authme
- model.rb
- authme.rb
Here are the contents of the gem. 这是宝石的内容。
# lib/authme.rb
require 'authme/version'
require 'authme/model'
module Authme
end
# lib/authme/model.rb
module Authme
module Model
extend ActiveSupport::Concern
included do
include ActiveModel::SecurePassword
has_secure_password validations: false
before_create :create_session_token
end
module ClassMethods
def new_session_token
SecureRandom.urlsafe_base64
end
def encrypt(token)
Digest::SHA1.hexdigest(token.to_s)
end
end
private
def create_session_token
self.session_token = self.class.encrypt(self.class.new_session_token)
end
end
end
I add this to my gemspec: 我将此添加到我的gemspec中:
spec.add_dependency "activesupport", "~> 4.0.1"
To test this, inside the terminal, I tried User.new_session_token
and got this error: 为了测试这一点,在终端内部,我尝试了
User.new_session_token
并得到了这个错误:
NoMethodError: undefined method `new_session_token' for User:Class
What am I doing wrong? 我究竟做错了什么? I really want to test this, but I'm out of my depth.
我真的很想测试一下,但是我不敢相信。 I'm not sure how to test that the class User has the included the gem module.
我不确定如何测试User类是否包含了gem模块。
The problem is that you're creating Authme::Model
and Authme::Model::ClassMethods
but you're never actually adding new_session_token
as class methods of Authme::Model
. 问题在于您正在创建
Authme::Model
和Authme::Model::ClassMethods
但实际上从未将new_session_token
添加为Authme::Model
类方法。
If you want to add these methods onto Authme::Model
you need to do something like 如果要将这些方法添加到
Authme::Model
,则需要执行以下操作
module Authme
module Model
module ClassMethods
# define all of your class methods here...
end
extend ClassMethods
end
end
The key part here is the Object#extend . 这里的关键部分是Object#extend 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.