/ Published in: Rails
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.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
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 !@voucher.nil? 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