module Maini::Utils::ActiveRecord::RandomString::ModelExtensions

Public Class Methods

included(base) click to toggle source
# File lib/maini/utils/active_record/random_string.rb, line 39
def self.included(base)
  base.extend ClassMethods
  base.before_validation :generate_random_strings
end

Public Instance Methods

generate_random_strings() click to toggle source
# File lib/maini/utils/active_record/random_string.rb, line 44
def generate_random_strings
  self.class.random_string_fields.each do |field, opts|
    if self.send(field).blank?
      if opts[:unique]
        until self.send(field)
          proposed_string = RandomString.random_string(opts[:type], opts)
          unless self.class.where(field => proposed_string).exists?
            self.send("#{field}=", proposed_string)
          end
        end
      else
        self.send("#{field}=", RandomString.random_string(opts[:type], opts))
      end
    end
  end
end