Skip to content

Commit

Permalink
refactering gtin
Browse files Browse the repository at this point in the history
  • Loading branch information
i2bskn committed Sep 11, 2013
1 parent 3fd880e commit 6972daa
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 12 deletions.
21 changes: 21 additions & 0 deletions lib/jancode/gtin.rb
Expand Up @@ -7,8 +7,29 @@ def initialize(company_prefix = nil, item_code = nil)
@item_code = item_code
end

def check_digit
validation
val = ((sum_even_numbers * 3) + sum_odd_numbers).to_s[-1].to_i
val == 0 ? 0 : 10 - val
end

def create
[@company_prefix, @item_code, check_digit].join
end

private
def sum_even_numbers
code = code_array.reverse
(0..(code.size - 1)).step(2).inject(0){|i,n| i += code[n].to_i}
end

def sum_odd_numbers
code = code_array.reverse
(1..(code.size - 1)).step(2).inject(0){|i,n| i += code[n].to_i}
end

def code_array
[@company_prefix, @item_code].join.chars
end
end
end
21 changes: 15 additions & 6 deletions lib/jancode/gtin13.rb
@@ -1,11 +1,20 @@
module Jancode
class GTIN13 < GTIN
def check_digit
code = [@company_prefix, @item_code].join.chars.map{|n| n.to_i}
even = (1..(code.size - 1)).step(2).inject(0){|i,n| i += code[n] * 3}
odd = (0..(code.size - 1)).step(2).inject(0){|i,n| i += code[n]}
val = (even + odd).to_s[-1].to_i
val == 0 ? 0 : 10 - val
def validation
valid_company_prefix @company_prefix
valid_item_code @item_code
raise "Is not 12 characters Item Code and GS1 Company Prefix to suit" if code_array.size != 12
end

private
def valid_company_prefix(company_prefix)
raise "GS1 Company Prefix is not String" unless company_prefix.is_a? String
raise "GS1 Company Prefix is not 7 or 9 characters" if company_prefix.size != 7 && company_prefix.size != 9
end

def valid_item_code(item_code)
raise "Item Code is not String" unless item_code.is_a? String
raise "Item Code is not 5 or 3 characters" if item_code.size != 3 && item_code.size != 5
end
end
end
21 changes: 15 additions & 6 deletions lib/jancode/gtin8.rb
@@ -1,11 +1,20 @@
module Jancode
class GTIN8 < GTIN
def check_digit
code = [@company_prefix, @item_code].join.chars.map{|n| n.to_i}
even = (0..(code.size - 1)).step(2).inject(0){|i,n| i += code[n] * 3}
odd = (1..(code.size - 1)).step(2).inject(0){|i,n| i += code[n]}
val = (even + odd).to_s[-1].to_i
val == 0 ? 0 : 10 - val
def validation
valid_company_prefix @company_prefix
valid_item_code @item_code
raise "Is not 7 characters Item Code and GS1 Company Prefix to suit" if code_array.size != 7
end

private
def valid_company_prefix(company_prefix)
raise "GS1 Company Prefix is not String" unless company_prefix.is_a? String
raise "GS1 Company Prefix is not 6 characters" if company_prefix.size != 6
end

def valid_item_code(item_code)
raise "Item Code is not String" unless item_code.is_a? String
raise "Item Code is not 1 characters" if item_code.size != 1
end
end
end

0 comments on commit 6972daa

Please sign in to comment.