Sha256: 2c697d85eb2795b70cded9375ca11ebf39b8a22677c8990433b8b0de06e051c0

Contents?: true

Size: 1.06 KB

Versions: 1

Compression:

Stored size: 1.06 KB

Contents

require 'coupon_code/version'
require 'securerandom'
require 'digest/sha1'

module CouponCode
  SYMBOL = '0123456789ABCDEFGHJKLMNPQRTUVWXY'
  PARTS  = 3
  LENGTH = 4

  def self.generate(options = { parts: PARTS })
    num_parts = options.delete(:parts)
    parts = []
    (1..num_parts).each do |i|
      part = ''
      (1...LENGTH).each { part << random_symbol }
      part << checkdigit_alg_1(part, i)
      parts << part
    end
    parts.join('-')
  end

  def self.validate(orig, num_parts = PARTS)
    code = orig.upcase
    code.gsub!(/[^#{SYMBOL}]+/, '')
    parts = code.scan(/[#{SYMBOL}]{#{LENGTH}}/)
    return if parts.length != num_parts
    parts.each_with_index do |part, i|
      data  = part[0...(LENGTH - 1)]
      check = part[-1]
      return if check != checkdigit_alg_1(data, i + 1)
    end
    parts.join('-')
  end

  def self.checkdigit_alg_1(orig, check)
    orig.split('').each_with_index do |c, _|
      k = SYMBOL.index(c)
      check = check * 19 + k
    end
    SYMBOL[check % 31]
  end

  def self.random_symbol
    SYMBOL[rand(SYMBOL.length)]
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
coupon_code-0.0.2 lib/coupon_code.rb