Generate codes for a online gift voucher


/ Published in: Rails
Save to your folder(s)

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.


Copy this code and paste it in your HTML
  1. Class Voucher < ActiveRecord::Base
  2. before_validation_on_create :generate_code
  3.  
  4. def generate_code
  5. code = create_code
  6.  
  7. #ensure that the voucher code is unique.
  8. @voucher = Voucher.find(:first, :conditions => "code = '#{code}'")
  9. code = create_code
  10. @voucher = Voucher.find(:first, :conditions => "code = '#{code}'")
  11. end
  12.  
  13. self.code = code
  14. end
  15.  
  16. protected
  17. def create_code
  18. chars = ("A".."Z").to_a
  19.  
  20. code = ""
  21. 1.upto(VOUCHER_CODE_LENGTH) { |i|
  22. code << chars[rand(chars.size-1)]
  23. if i % 4 == 0 && i < VOUCHER_CODE_LENGTH
  24. code << "-"
  25. end
  26. }
  27. return code
  28. end
  29. end

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.