module HasRandomToken extend ActiveSupport::Concern module ClassMethods def has_random_token(attribute: :token, unique: false, length: 32) require 'securerandom' define_method("regenerate_#{attribute}") { update! attribute => self.class.generate_random_token(attribute, unique, length) } before_create { self.send("#{attribute}=", self.class.generate_random_token(attribute, unique, length)) unless self.send("#{attribute}?")} end def generate_random_token(attribute, unique, length) begin token = SecureRandom.base64(length)[0 .. length - 1] end while unique && self.exists?(attribute => token) return token end end end ActiveRecord::Base.send :include, HasRandomToken