Class: GS1::Barcode::Segment

Inherits:
Object
  • Object
show all
Defined in:
lib/gs1/barcode/segment.rb

Overview

A segment of a barcode. Retrives a single segment and keeps the rest.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(data, separator: GS1.configuration.barcode_separator) ⇒ Segment

Returns a new instance of Segment.



8
9
10
11
# File 'lib/gs1/barcode/segment.rb', line 8

def initialize(data, separator: GS1.configuration.barcode_separator)
  @data = data.to_s.chars
  @separator = separator
end

Instance Attribute Details

#dataObject (readonly)

Returns the value of attribute data.



6
7
8
# File 'lib/gs1/barcode/segment.rb', line 6

def data
  @data
end

#separatorObject (readonly)

Returns the value of attribute separator.



6
7
8
# File 'lib/gs1/barcode/segment.rb', line 6

def separator
  @separator
end

Instance Method Details

#errorsObject



63
64
65
# File 'lib/gs1/barcode/segment.rb', line 63

def errors
  @errors ||= []
end

#recordObject

Fetch the two first characters (interpreted as AI) from the remaining data and try to find record class. If no record class was found, fetch a third character and try again, and then finally a forth, as no AI currently have more then 4 characters.



23
24
25
26
27
# File 'lib/gs1/barcode/segment.rb', line 23

def record
  @record ||= process_ai_variants(2) ||
              process_ai_variants(1) ||
              process_ai_variants(1)
end

#record_dataObject



29
30
31
32
33
# File 'lib/gs1/barcode/segment.rb', line 29

def record_data
  return unless record

  @record_data ||= _record_data
end

#restObject



35
36
37
38
39
# File 'lib/gs1/barcode/segment.rb', line 35

def rest
  record_data # Trigger segment retrieval

  @data.join
end

#to_paramsObject



13
14
15
16
17
# File 'lib/gs1/barcode/segment.rb', line 13

def to_params
  return [] unless record

  [record.underscore_name, record_data]
end

#valid?Boolean

Returns:

  • (Boolean)


41
42
43
44
45
46
47
# File 'lib/gs1/barcode/segment.rb', line 41

def valid?
  errors.clear

  validate

  errors.empty?
end

#validateObject



49
50
51
52
53
54
55
# File 'lib/gs1/barcode/segment.rb', line 49

def validate
  if record
    errors << "Unable to retrieve data to #{record}" unless record_data
  else
    errors << "Unable to retrieve record from application identifier(s) #{ai_variants.join(', ')}"
  end
end

#validate!Object

Raises:



57
58
59
60
61
# File 'lib/gs1/barcode/segment.rb', line 57

def validate!
  return true if valid?

  raise InvalidTokenError, errors.join(', ')
end