thetron / mongoid_token Goto Github PK
View Code? Open in Web Editor NEWA little random, unique token generator for Mongoid documents.
License: MIT License
A little random, unique token generator for Mongoid documents.
License: MIT License
Tokens should also be able to be generated from patterns. Something like:
class Person
include Mongoid::Document
include Mongoid::Token
field :name
token :pattern => /[0-9]{5}-[A-Za-z]{3}/
end
Consider using randexp to support this.
Upon following installation instructions, I got an uninitialized constant Mongoid::Token error.
Token declaration was for my user model:
class User
include Mongoid::Document
include Mongoid::Timestamps
include Mongoid::Token
FIELDS HERE
token :length => 6
Rails version 3.2.9, Ruby 1.9.3v327 on x86_64_darwin11.4.2, Mongoid 3.0.14, 3.0.13 and Mongoid_token 1.1.0
If this has been brought up before, I can't find it, but I've added this gem after having built several users in the app; how do I update them all to have their token generated?
Refer #11.
If I create an object and some embedded children at once, then call .save on it, it seems like only the root object gets a token, and the embedded ones don't ever get tokens generated for them.
Here's a gist of what I'm doing:
https://gist.github.com/anonymous/45942d8f240da1288852
s.add_dependency 'mongoid', '~> 3.0'
Guys are you planning to support mongoid 4.0?
I get:
Bundler could not find compatible versions for gem "mongoid":
In snapshot (Gemfile.lock):
mongoid (4.0.0)In Gemfile:
mongoid_token (>= 0) ruby depends on
mongoid (~> 3.0) rubyRunning
bundle update
will rebuild your snapshot from scratch, using only
the gems in your Gemfile, which may resolve the conflict.
When trying to use with 4.0
When using a Mongoid class that uses mongoid_token, if a unique index is violated during insertion, a "NoMethodError" is raised instead of the appropriate error. Simply removing Mongoid::Token from the class results in the appropriate Mongoid error being raised.
This is preventing me from being able to catch the appropriate error and handle the exception. BTW - I'm using the latest 'patch/collisions-define-method' branch.
Here is the stack trace that is raised incorrectly:
NoMethodError: undefined method `errors' for nil:NilClass
mongoid/persistence.rb:277:in `block in create!'
fail_validate!(doc) unless doc.insert.errors.empty?
mongoid/threaded/lifecycle.rb:173:in `_creating'
yield
mongoid/persistence.rb:272:in `create!'
_creating do
tasks/photo_upload_controller.rb:20:in `upload'
photo = Photo.create!(photo_params)
When mongoid clones a model object, it copies over all of the fields, but not the instance variables. This results in the @token_field_name instance variable being nil.
When you try to save the cloned model, mongoid_token runs the code "@token_field_name.to_sym" which results in the following exception: (I'm using 1.0.0, but it looks like this would still be an issue in 1.1.0)
undefined method to_sym' for nil:NilClass mongoid_token (1.0.0) lib/mongoid_token.rb:91:in
create_token_if_nil'
mongoid_token (1.0.0) lib/mongoid_token.rb:24:in `block in token'
I just need a valid token, rather than actually saving the document.
for example: form.entries.find token
will query by _id instead of token
A feature request... I'd like to use the gem to generate tokens in addition to mongoid-slug, so it would be good if you could specify an option not to override to_param.
Can it create unique token for embedded documents?
Hi,
Found something that might be a bug. Models are not checked for collisions when instantiated with create!
:
it 'tries to resolve collisions when instantiated with create!' do
link = Link.create!(url: 'http://example.com/1')
Link.any_instance.stub(:generate_token).and_return(link.token)
expect { Link.create!(url: 'http://example.com/2') }
.to raise_error(Mongoid::Token::CollisionRetriesExceeded)
end
This is happening because create!
does not call save
like create
(without a bang) does.
Hey all,
I'm seeing the following error in token.rb on rails 4.0 with mongoid 4.0 (i know .. unsupported).
"implicit argument passing of super from method defined by define_method() is not supported. Specify all arguments explicitly"
It looks like it's related to the super call on token.rb:42. I've been trying to figure out the exact fix here, but banging my head against the wall.
Any suggestions?
I am often running into random errors with Mongoid::Token, it seems that some of my constants are tried to be resolved from Mongoid::Token::Collisions scope.
Like
uninitialized constant Mongoid::Token::Collisions::ProfilesController
uninitialized constant Mongoid::Token::Collisions::RegistrationsController
Often prefixing my controller class names with ::
(::ProfilesController
) do help but not always
Actually the problem may come from here : I have model classes that have the same name as a module I use to prefix my controller
class Admin
token ...
end
class Admin::ProfilesController < ApplicationController
end
# => uninitialized constant Mongoid::Token::Collisions::ProfilesController
My Stack Trace
activesupport (5.0.0.1) lib/active_support/inflector/methods.rb:283:in `const_get'
activesupport (5.0.0.1) lib/active_support/inflector/methods.rb:283:in `block in constantize'
activesupport (5.0.0.1) lib/active_support/inflector/methods.rb:266:in `each'
activesupport (5.0.0.1) lib/active_support/inflector/methods.rb:266:in `inject'
activesupport (5.0.0.1) lib/active_support/inflector/methods.rb:266:in `constantize'
actionpack (5.0.0.1) lib/action_dispatch/http/request.rb:93:in `controller_class'
actionpack (5.0.0.1) lib/action_dispatch/routing/route_set.rb:44:in `controller'
actionpack (5.0.0.1) lib/action_dispatch/routing/route_set.rb:30:in `serve'
actionpack (5.0.0.1) lib/action_dispatch/journey/router.rb:39:in `block in serve'
actionpack (5.0.0.1) lib/action_dispatch/journey/router.rb:26:in `each'
actionpack (5.0.0.1) lib/action_dispatch/journey/router.rb:26:in `serve'
actionpack (5.0.0.1) lib/action_dispatch/routing/route_set.rb:725:in `call'
rack-attack (5.0.1) lib/rack/attack.rb:147:in `call'
omniauth (1.3.2) lib/omniauth/strategy.rb:186:in `call!'
omniauth (1.3.2) lib/omniauth/strategy.rb:164:in `call'
omniauth (1.3.2) lib/omniauth/strategy.rb:186:in `call!'
omniauth (1.3.2) lib/omniauth/strategy.rb:164:in `call'
rack-tracker (1.1.0) lib/rack/tracker.rb:34:in `call'
rack-utm (0.0.2) lib/rack-utm.rb:59:in `call'
warden (1.2.6) lib/warden/manager.rb:35:in `block in call'
warden (1.2.6) lib/warden/manager.rb:34:in `catch'
warden (1.2.6) lib/warden/manager.rb:34:in `call'
rack (2.0.1) lib/rack/etag.rb:25:in `call'
rack (2.0.1) lib/rack/conditional_get.rb:25:in `call'
rack (2.0.1) lib/rack/head.rb:12:in `call'
rack (2.0.1) lib/rack/session/abstract/id.rb:222:in `context'
rack (2.0.1) lib/rack/session/abstract/id.rb:216:in `call'
actionpack (5.0.0.1) lib/action_dispatch/middleware/cookies.rb:613:in `call'
actionpack (5.0.0.1) lib/action_dispatch/middleware/callbacks.rb:38:in `block in call'
activesupport (5.0.0.1) lib/active_support/callbacks.rb:97:in `__run_callbacks__'
activesupport (5.0.0.1) lib/active_support/callbacks.rb:750:in `_run_call_callbacks'
activesupport (5.0.0.1) lib/active_support/callbacks.rb:90:in `run_callbacks'
actionpack (5.0.0.1) lib/action_dispatch/middleware/callbacks.rb:36:in `call'
actionpack (5.0.0.1) lib/action_dispatch/middleware/executor.rb:12:in `call'
actionpack (5.0.0.1) lib/action_dispatch/middleware/remote_ip.rb:79:in `call'
actionpack (5.0.0.1) lib/action_dispatch/middleware/debug_exceptions.rb:49:in `call'
web-console (3.3.1) lib/web_console/middleware.rb:131:in `call_app'
web-console (3.3.1) lib/web_console/middleware.rb:28:in `block in call'
web-console (3.3.1) lib/web_console/middleware.rb:18:in `catch'
web-console (3.3.1) lib/web_console/middleware.rb:18:in `call'
actionpack (5.0.0.1) lib/action_dispatch/middleware/show_exceptions.rb:31:in `call'
railties (5.0.0.1) lib/rails/rack/logger.rb:36:in `call_app'
railties (5.0.0.1) lib/rails/rack/logger.rb:24:in `block in call'
activesupport (5.0.0.1) lib/active_support/tagged_logging.rb:70:in `block in tagged'
activesupport (5.0.0.1) lib/active_support/tagged_logging.rb:26:in `tagged'
activesupport (5.0.0.1) lib/active_support/tagged_logging.rb:70:in `tagged'
railties (5.0.0.1) lib/rails/rack/logger.rb:24:in `call'
ahoy_matey (1.5.2) lib/ahoy/engine.rb:22:in `call_with_quiet_ahoy'
request_store (1.3.1) lib/request_store/middleware.rb:9:in `call'
actionpack (5.0.0.1) lib/action_dispatch/middleware/request_id.rb:24:in `call'
rack (2.0.1) lib/rack/method_override.rb:22:in `call'
rack (2.0.1) lib/rack/runtime.rb:22:in `call'
activesupport (5.0.0.1) lib/active_support/cache/strategy/local_cache_middleware.rb:28:in `call'
actionpack (5.0.0.1) lib/action_dispatch/middleware/executor.rb:12:in `call'
actionpack (5.0.0.1) lib/action_dispatch/middleware/static.rb:136:in `call'
rack (2.0.1) lib/rack/sendfile.rb:111:in `call'
rack-cors (0.4.0) lib/rack/cors.rb:80:in `call'
railties (5.0.0.1) lib/rails/engine.rb:522:in `call'
puma (3.6.0) lib/puma/configuration.rb:225:in `call'
puma (3.6.0) lib/puma/server.rb:578:in `handle_request'
puma (3.6.0) lib/puma/server.rb:415:in `process_client'
puma (3.6.0) lib/puma/server.rb:275:in `block in run'
puma (3.6.0) lib/puma/thread_pool.rb:116:in `block in spawn_thread'
Rendering /Users/Cyril/.rvm/gems/ruby-2.3.3/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/routing_error.html.erb within rescues/layout
Rendering /Users/Cyril/.rvm/gems/ruby-2.3.3/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb
Rendered /Users/Cyril/.rvm/gems/ruby-2.3.3/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb (3.9ms)
Rendered collection of /Users/Cyril/.rvm/gems/ruby-2.3.3/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/routes/_route.html.erb [301 times] (124.3ms)
Rendered collection of /Users/Cyril/.rvm/gems/ruby-2.3.3/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/routes/_route.html.erb [5 times] (3.0ms)
Rendered collection of /Users/Cyril/.rvm/gems/ruby-2.3.3/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/routes/_route.html.erb [1 times] (0.6ms)
Rendered collection of /Users/Cyril/.rvm/gems/ruby-2.3.3/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/routes/_route.html.erb [2 times] (1.0ms)
Rendered /Users/Cyril/.rvm/gems/ruby-2.3.3/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/routes/_table.html.erb (2.4ms)
Rendering /Users/Cyril/.rvm/gems/ruby-2.3.3/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb
Rendered /Users/Cyril/.rvm/gems/ruby-2.3.3/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb (2.6ms)
Rendered /Users/Cyril/.rvm/gems/ruby-2.3.3/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/routing_error.html.erb within rescues/layout (325.7ms)
I just found that Mongoid currently cannot enforce unique index within of single document (for example a embeds_many
relationship).
I'm using embeds_many
and set a token to the embeded document:
token field_name: :token, length: 1, contains: :fixed_numeric_no_leading_zeros
Then I generate a lot of embeded documents (more than 10), all of them can be saved successfully, and their tokens have duplications.
I love the gem, but unfortunately I can' t use it right now as it is conflicting with the gem we are using for version management.
https://github.com/stouset/version
If I get a chance I will try and dig into it more, but I thought I'd bring it up in the meantime.
No errors are thrown until you try and do something that touches the Version gem's functionality such as the rake tasks.
I just tried adding multiple tokens to an existing User model:
class User
token :length => 16
token :length => 6, :contains => :alpha_lower, :field_name => :sharing_token
If I then do
u = User.last
u.save
u.sharing_token
=> "5SeO8IsFSFWOSWyN"
u.token
=> "lmcVQfv1GurWb1ZU"
And then:
User.new.save
=> SystemStackError: stack level too deep
Thanks.
Is it possible to remove "i", "l", "o", "0" characters that introduce common human error
"iIlLOo0"
Is there any plan/timeline to add support for mongoid 6 and rails 5 ?
I'm using mongoid_token for my users authorization_token, and it does a great job of generating that token when the users are created. I added this feature though after already having users, so I'd like to be able to generate tokens for those pre-existing users through the rails console or by running a rake command.
Thoughts please?
Hey @thetron, I have some code which clones a class, but for token classes I get an error.
Repro steps:
require 'mongoid'
require 'mongoid_token'
class Person
include Mongoid::Document
include Mongoid::Token
field :name
token
end
Person.clone
this line yields a NoMethodError.
I can't tell whether self.token = nil
is a relic of a previous implementation or I just am missing something. As a work-around, I have added def self.token=(*); end
to classes which include mongoid_token, but want to make sure I'm not setting myself up for some headaches down the road.
Thanks!
Thanks for this great tool for generating tokens!
Now i have a relation between two collections, for example a company has_many
staffs, and a staff belongs_to
a company. I'v already add tokens to each model, but when I created a new staff for a company, the foreign key is still using company's object id (_id
field), how can i use company's token
field as the foreign key?
I have the following 2 models
class Student < User
token pattern: "S_%d8"
belongs_to :parent
end
class Parent < User
token pattern: "P_%d8"
has_many :students
end
on Rails_admin Parent Page when I try to save the Parent without any changes I get the following error
Problem: Document not found for class Student with attributes {:token=>[]}.
Summary: When calling Student.find_by with a hash of attributes, all attributes provided must match a document in the database or this error will be raised.
the same problem also exists when I try to add any student to the parent class via Rails admin...
Problem: Document not found for class Student with attributes {:token=>[BSON::ObjectId('54528faf416264e024000000')]}.
Summary: When calling Student.find_by with a hash of attributes, all attributes provided must match a document in the database or this error will be raised.
One Important thing to note is when I add skip_finders: true
to Student
model every thing works as expected (but without the mongoid_token support for Student
s of course)
Hello,
I'm very new to Ruby on Rails. I wanted to use Mongoid_Token to generate short URLs. Unfortunately, after installing the gem, and adding the relevant lines in my model class, I get the following error:
Problem:
Invalid index specification on Page: token, {:unique=>true}
Summary:
Indexes in Mongoid are defined as a hash of field name and direction/2d pairs, with a hash for any additional options.
Resolution:
Ensure that the index conforms to the correct syntax and has the correct options.Valid options are:
background: true|false
drop_dups: true|false
name: 'index_name'
sparse: true|false
unique: true|falseValid types are: 1, -1, '2d'
Example:
class Band
include Mongoid::Document
index({ name: 1, label: -1 }, { sparse: true })
index({ location: '2d' }, { background: true })
end
Unfortunately, my google-fu didn't help me much here. Any ideas?
If relevant, I'm using Mongoid 3 with Rails 3.2.
Should they not? I thought updating your entire bundle for the sake of one gem was a bad idea...
Great gem!
PS. The gem version should not be pegged at 2.0.0. That's an old release. ~> 2.0 worked for me.
For some models it seems reasonable to just replace _id field with the token. Kind of a feature request. What do you think?
I like this gem, but what happens if it generates duplicate token???
Also, if all possible combinations are already in db, what happens then? Do user manually have to increase the length of the token?
The method below in token.rb
call super with param *args
. However, the args does not exist. In previous version it is inside token(*args)
method.
It seems a mistake after extracting it as a method out of token(*args)
method.
private
def override_to_param(options)
self.send(:define_method, :to_param) do
self.send(options.field_name) || super(*args)
end
end
Mongoid::Token
doesn't generate tokens for old documents, so their token value stays nil
.
Given the following model:
class ATest
include Mongoid::Document
include Mongoid::Token
field :name, :type => String
field :is_true, :type => Boolean
token :length => 3
validates :name, :presence => true
end
And the following spec:
require 'spec_helper'
describe ATest do
describe 'draft style' do
it 'is required' do
style = ATest.create(:name => nil, :is_true => false)
style.should have(1).errors_on(:name)
style.name = 'Test Value'
style.should have(:no).errors_on(:name)
end
it 'can be false' do
style = ATest.create(:name => "Tournament", :is_true => true)
style.should have(:no).errors_on(:name)
end
end
end
then you'll receive the following warning from rspec:
DEPRECATION WARNING: ActiveSupport::SecureRandom is deprecated! Use SecureRandom instead.
If you comment out the Mongoid::Token inclusion, the warning goes away.
We are using Mongoid ~2.3, sorcery ~0.7 and rails 3.1.0
I have tried to find in the mongoid_token source where there are calls to ActiveSupport::SecureRandom methods, but have not been able to trace them down.
Any guidance would be appreciated.
Video.find(["x3v98", "kd2o1"])
Returns Mongoid::Errors::DocumentNotFound exception: Document not found for class Video with attributes {:token=>["x3v98", "kd2o1"]}.
It also breaks the default mongoid find by multiple ids:
Video.find(["528af2997e311132ae000003", "510466be72fbd5abf000f937"])
Also returns DocumentNotFound exception: Document not found for class Video with attributes {:token=>["528af2997e311132ae000003", "510466be72fbd5abf000f937"]}.
My mongo object embeds several sub-doc, i add token
to both the main doc and sub-doc, but token
field is not generated for sub-doc. Is this by design, or is there any other things i need do?
/home/xwsaw/.rvm/gems/ruby-2.0.0-p0/bundler/gems/mongoid_token-4009f4eefd36/lib/mongoid/token/collision_resolver.rb:28:in alias_method_with_collision_resolution': private method
define_method' called fo
r Video:Class (NoMethodError)
This is the error I am getting when I try to run the rails server.
The gem is working fine locally, but when deployed to Heroku I consistently get CollisionRetriesExceeded exceptions - even though the token is getting generated correctly and the data is successfully saving to MongoHQ.
I don't know if this is related, but the README mentions a config value that no longer exists in Mongoid 3.x To take advantage of this, one must set persist_in_safe_mode = true in your Mongoid configuration.
I've tried changing my Mongoid config to:
options:
consistency: :eventual
safe: true
and:
options:
consistency: :strong
safe: true
I suggest the MIT licence. Thanks.
Hello @thetron , and thanks for this plugin, just recently found it out.
Ok, half my OCD, half maybe avoid future confusion and chaos:
I'm going in plugins to suggest correct gem naming:
http://guides.rubygems.org/name-your-gem/
To fix you could remove lib/mongoid_token.rb or add a deprecated message to it.
gem 'mongoid-token'
require 'mongoid/token'
include Mongoid::Token
All good then. Thank you!
I realize you need to create another rubygem, with hyphen and rename the project here.
Up to you, I'm going to do that in a bad named plugin I have, github now stores old urls and redirects, sounds fine.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.