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