Sha256: b218f091fe473b9bba0759f8972f42c2fee264c9b89aa1de6e7a03ecf8197595
Contents?: true
Size: 1.2 KB
Versions: 1
Compression:
Stored size: 1.2 KB
Contents
module JT::Rails::Tokenizable::Tokenize extend ActiveSupport::Concern included do |base| before_validation :jt_rails_generate_tokens, on: :create base.class_eval do # jt_rails_token_fields is shared only by a class and its subclass def self.jt_rails_token_fields class_variable_set(:@@jt_rails_token_fields, HashWithIndifferentAccess.new) if !class_variable_defined?(:@@jt_rails_token_fields) class_variable_get(:@@jt_rails_token_fields) end end end class_methods do def tokenize(field, options = {}) jt_rails_token_fields[field.to_sym] = options if options.fetch(:valiations, true) validates field, presence: true, uniqueness: true end end end def jt_rails_generate_tokens for field in self.class.jt_rails_token_fields.keys generate_new_token(field) end end def generate_new_token(field) size = self.class.jt_rails_token_fields[field.to_sym].fetch(:size, 32) only_digits = self.class.jt_rails_token_fields[field.to_sym].fetch(:only_digits, false) self[field.to_sym] = loop do random_token = only_digits ? SecureRandom.random_number(10**size) : SecureRandom.hex(size) break random_token unless self.class.exists?(field => random_token) end end end
Version data entries
1 entries across 1 versions & 1 rubygems
Version | Path |
---|---|
jt-rails-tokenizable-1.1.1 | lib/tokenize.rb |