Sha256: ead118e7ec689156e21016f914e1c6f72ef50495242c4105d7a6eeb8007a87b6
Contents?: true
Size: 852 Bytes
Versions: 1
Compression:
Stored size: 852 Bytes
Contents
require "uniq_token/version" module UniqToken extend ActiveSupport::Concern def random_str length chars = [('a'..'z'), ('A'..'Z'), ('0'..'9')].map(&:to_a).flatten (0...length).map { chars[rand(chars.length)] }.join end module ClassMethods def unique_token field, options prefix = options[:prefix].present? ? options[:prefix] : '' length = options[:length].to_i > 0 ? options[:length].to_i : 64 suffix = options[:suffix].present? ? options[:suffix] : '' before_validation { |record| if record[field].blank? record[field] = loop do random_token = "#{prefix}#{random_str(length)}#{suffix}" break random_token unless record.class.exists?("#{field}": random_token) end end } end end end class ActiveRecord::Base include UniqToken end
Version data entries
1 entries across 1 versions & 1 rubygems
Version | Path |
---|---|
uniq_token-0.1.0 | lib/uniq_token.rb |