Revision: 11792
Initial Code
Initial URL
Initial Description
Initial Title
Initial Tags
Initial Language
at February 18, 2009 20:03 by jordanbrock
Initial Code
Class Voucher < ActiveRecord::Base
before_validation_on_create :generate_code
def generate_code
code = create_code
#ensure that the voucher code is unique.
@voucher = Voucher.find(:first, :conditions => "code = '#{code}'")
while [email protected]?
code = create_code
@voucher = Voucher.find(:first, :conditions => "code = '#{code}'")
end
self.code = code
end
protected
def create_code
chars = ("A".."Z").to_a
code = ""
1.upto(VOUCHER_CODE_LENGTH) { |i|
code << chars[rand(chars.size-1)]
if i % 4 == 0 && i < VOUCHER_CODE_LENGTH
code << "-"
end
}
return code
end
end
Initial URL
Initial Description
Can be used to generate a random code for an online voucher. You just need to set VOUCHER_CODE_LENGTH in your environment.rb or similar.
Initial Title
Generate codes for a online gift voucher
Initial Tags
ruby
Initial Language
Rails