Rails 3: Generate unique codes (coupons)

后端 未结 6 1178
借酒劲吻你
借酒劲吻你 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: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
    

提交回复
热议问题