Skip to content

Instantly share code, notes, and snippets.

@curt
Created February 9, 2010 14:41
Show Gist options
  • Save curt/299251 to your computer and use it in GitHub Desktop.
Save curt/299251 to your computer and use it in GitHub Desktop.
Create unique random attributes in ActiveRecord
module RandomAttributes
def self.included(controller)
controller.send :extend, ClassMethods
controller.send :include, InstanceMethods
end
module ClassMethods
def random_attribute(attr_sym, key_length = 10)
cattr_accessor :random_attributes
validates_presence_of attr_sym
validates_uniqueness_of attr_sym
self.random_attributes = ((random_attributes || []) << {:attr_sym => attr_sym, :key_length => key_length})
end
end
module InstanceMethods
def save(perform_validation = true)
self.class.random_attributes.each do |r|
validate_random_attribute(r[:attr_sym], r[:key_length])
end
super(perform_validation)
end
def save!
self.class.random_attributes.each do |r|
validate_random_attribute(r[:attr_sym], r[:key_length])
end
super
end
end
protected
def validate_random_attribute(attr_sym, key_length = 10)
set_sym = "#{attr_sym}=".to_sym
while !self.valid? && self.errors.on(attr_sym)
self.send(set_sym, random_string(key_length))
end
end
def random_string(length = 10)
srand
Array.new(length){ rand(36).to_s(36) }.to_s
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment