Module: CouponCode
- Defined in:
- lib/coupon_code.rb,
lib/coupon_code/version.rb
Constant Summary collapse
- SYMBOL =
"0123456789ABCDEFGHJKLMNPQRTUVWXY"- PARTS =
3- LENGTH =
4- VERSION =
"0.0.3".freeze
Class Method Summary collapse
- .checkdigit_alg_1(orig, check) ⇒ Object
- .generate(options = {parts: PARTS, part_length: LENGTH}) ⇒ Object
- .random_symbol ⇒ Object
- .validate(orig, num_parts = PARTS, part_length = LENGTH) ⇒ Object
Class Method Details
.checkdigit_alg_1(orig, check) ⇒ Object
37 38 39 40 41 42 43 |
# File 'lib/coupon_code.rb', line 37 def self.checkdigit_alg_1(orig, check) orig.chars.each_with_index do |c, _| k = SYMBOL.index(c) check = check * 19 + k end SYMBOL[check % 31] end |
.generate(options = {parts: PARTS, part_length: LENGTH}) ⇒ Object
10 11 12 13 14 15 16 17 18 19 20 21 22 |
# File 'lib/coupon_code.rb', line 10 def self.generate( = {parts: PARTS, part_length: LENGTH}) num_parts = .delete(:parts) length_of_parts = .delete(:part_length) || LENGTH parts = [] (1..num_parts).each do |i| part = "" (1...length_of_parts).each { part << random_symbol } part << checkdigit_alg_1(part, i) parts << part end parts.join("-") end |
.random_symbol ⇒ Object
45 46 47 |
# File 'lib/coupon_code.rb', line 45 def self.random_symbol SYMBOL[rand(SYMBOL.length)] end |
.validate(orig, num_parts = PARTS, part_length = LENGTH) ⇒ Object
24 25 26 27 28 29 30 31 32 33 34 35 |
# File 'lib/coupon_code.rb', line 24 def self.validate(orig, num_parts = PARTS, part_length = LENGTH) code = orig.upcase code.gsub!(/[^#{SYMBOL}]+/o, "") parts = code.scan(/[#{SYMBOL}]{#{part_length}}/) return if parts.length != num_parts parts.each_with_index do |part, i| data = part[0...(part_length - 1)] check = part[-1] break if check != checkdigit_alg_1(data, i + 1) end parts.join("-") end |