Rails 3: Generate unique codes (coupons)

后端 未结 6 1176
借酒劲吻你
借酒劲吻你 2021-01-30 18:29

What\'s the best way to generate unique codes to use as coupon codes?

Thanks.

相关标签:
6条回答
  • 2021-01-30 19:01

    Maybe try this, seems to be more proof than just generating some random key. They say: UUID generator for producing universally unique identifiers based on RFC 4122 (http://www.ietf.org/rfc/rfc4122.txt). http://rubygems.org/gems/uuid

    gem install uuid
    cd /myproject/path
    uuid-setup
    

    In your code

    require_gem 'uuid'
    my_unique_id_var = UUID.new
    

    Reference: http://railsforum.com/viewtopic.php?id=12616#p44545

    0 讨论(0)
  • 2021-01-30 19:03

    You can do something like this too:

    chars = ('a'..'z').to_a + ('A'..'Z').to_a
    def String.random_alphanumeric(size=16)
        (0...size).collect { chars[Kernel.rand(chars.length)] }.join
    end
    

    But then you would have to compare against a database to make sure it is not used yet.

    0 讨论(0)
  • 2021-01-30 19:10

    What you want is to generate a GUID. See here:

    guid generator in ruby

    0 讨论(0)
  • 2021-01-30 19:15

    Note: There is a same question

    Recently I wrote coupon-code gem that does exactly the same thing. The algorithm borrowed from Algorithm::CouponCode CPAN module.

    A coupon code should not only be unique, but also easy to read and type while it still is secure. Neil's explanation and solution is great. This gem provides a convenient way to do it and a bonus validation feature.

    >> require 'coupon_code'
    >> code = CouponCode.generate
    => "1K7Q-CTFM-LMTC"
    >> CouponCode.validate(code)
    => "1K7Q-CTFM-LMTC"
    >> CouponCode.validate('1K7Q-CTFM-LMTO') # Invalid code
    => nil
    
    0 讨论(0)
  • 2021-01-30 19:16

    In Ruby's standard library there is SecureRandom for this:

    SecureRandom.hex(3)
    

    The length of the output is double of what the length input specified.

    0 讨论(0)
  • 2021-01-30 19:16

    If you don't want to waste comparing against the database (not a super expensive operation), you can guarantee that Time is always unique because it only occurs once

    md5(Time.now.to_i.to_s+Time.now.usec.to_s)
    
    0 讨论(0)
提交回复
热议问题