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. while !@voucher.nil?
  10. code = create_code
  11. @voucher = Voucher.find(:first, :conditions => "code = '#{code}'")
  12. end
  13.  
  14. self.code = code
  15. end
  16.  
  17. protected
  18. def create_code
  19. chars = ("A".."Z").to_a
  20.  
  21. code = ""
  22. 1.upto(VOUCHER_CODE_LENGTH) { |i|
  23. code << chars[rand(chars.size-1)]
  24. if i % 4 == 0 && i < VOUCHER_CODE_LENGTH
  25. code << "-"
  26. end
  27. }
  28. return code
  29. end
  30. end

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.