Tokenable allows you to generate unique tokens on ActiveRecord model attributes.
Tokenable supports SecureRandom methods :
- base64
- urlsafe_base64
- hex
- random_bytes
- random_number
- uuid
Generation can be triggered manually and / or with an ActiveRecord Callback.
Add this line to your application's Gemfile:
gem 'tokenable', github: 'rdelandesen/tokenable'
And then execute:
$ bundle
class User < ActiveRecord::Base
tokenable.config do |c|
c.attr = :token
c.n = 42 # length in bytes
c.meth0d = :urlsafe_base64
c.callback = :before_create
end
end
user = User.new
user.tokenable.generate
user.token
# => "Zx7E92QSldsjiFnu9PWCtHkwbpR"
class User < ActiveRecord::Base
tokenable.config do |c|
# [...]
c.attrs = %i(token secure_id)
end
end
class User < ActiveRecord::Base
tokenable.config do |c|
# [...]
c.attrs = %i(token secure_id)
c.n = 10..22
end
end
This will apply a random length on each attribute :
user = User.new
user.tokenable.generate
user.token
# => "w6qLICRtZYShB9ZBkAX-Dvxx"
user.secure_id
# => "jtj6JNDOOLZP-asWZQ"
class User < ActiveRecord::Base
tokenable.config do |c|
# [...]
c.attrs = %i(token secure_id)
c.meth0d = %w(urlsafe_base64 uuid)
end
end
This will apply a random method on each attribute :
user = User.new
user.tokenable.generate
user.token
# => "w6qLICRtZYShB9ZBkAX" # urlsafe_base64
user.secure_id
# => "7a440004c9b1b1797cf211da54c2c641" # UUID
Bug reports and pull requests are welcome on GitHub at https://github.com/rdelandesen/tokenable.
The gem is available as open source under the terms of the MIT License.