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. 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  

You need to login to post a comment.