Ruby on rails 如何包含gem';Rails模型中的s类方法?
我正在学习如何写宝石。我想添加一些我将在Rails的用户模型中使用的方法Ruby on rails 如何包含gem';Rails模型中的s类方法?,ruby-on-rails,ruby,gem,Ruby On Rails,Ruby,Gem,我正在学习如何写宝石。我想添加一些我将在Rails的用户模型中使用的方法 # 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' 现在,在我的宝石里,我有以下几点: - authme - lib + au
# 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'
现在,在我的宝石里,我有以下几点:
- authme
- lib
+ authme
- model.rb
- authme.rb
以下是宝石的内容
# 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
我将此添加到我的gemspec中:
spec.add_dependency "activesupport", "~> 4.0.1"
为了测试这一点,在终端内部,我尝试了User.new\u session\u token
,但出现了以下错误:
NoMethodError: undefined method `new_session_token' for User:Class
我做错了什么?我真的很想测试一下,但我做得太过火了。我不确定如何测试类用户是否包含gem模块。问题是您正在创建
Authme::Model
和Authme::Model::ClassMethods
,但您从未实际添加新会话\u令牌作为Authme::Model
的类方法
如果要将这些方法添加到Authme::Model
中,需要执行以下操作
module Authme
module Model
module ClassMethods
# define all of your class methods here...
end
extend ClassMethods
end
end
这里的关键部分是。您是否在Gemfile中定义了gem的路径,以及bundle更新?我运行了bundle更新。至于定义路径,我不知道你的意思是什么。如果你想让rails在你的gem中获取更改,那么你必须在Gemfile中为该gem定义路径。例如gem'authme',path:/home/anil/path-to-gem谢谢,但我认为这不是问题所在。每次对gem进行更改时,我都会安装和卸载gem。我已经绑定了Rails和gem。我想我的代码出了问题。