Posted By

jordanbrock on 02/18/09


Tagged

random ruby rubyonrails


Versions (?)

Who likes this?

3 people have marked this snippet as a favorite

webstic
octoberborn
kukhtenko


Generate codes for a online gift voucher


 / Published in: Rails
 

Can be used to generate a random code for an online voucher. You just need to set VOUCHERCODELENGTH in your environment.rb or similar.

  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  

You need to login to post a comment.