Class: X12::Parser

Inherits:
Object
  • Object
show all
Defined in:
lib/x12/parser.rb

Overview

Main class for creating X12 parsers and factories.

Constant Summary collapse

MS_DEVICES =

These constitute prohibited file names under Microsoft

[
  'CON',
  'PRN',
  'AUX',
  'CLOCK$',
  'NUL',
  'COM1',
  'LPT1',
  'LPT2',
  'LPT3',
  'COM2',
  'COM3',
  'COM4',
].freeze

Instance Method Summary collapse

Constructor Details

#initialize(file_name, custom_file: false) ⇒ void

Creates a parser out of a definition.

Parameters:

  • file_name (String)
  • custom_file (Boolean) (defaults to: false)

    (false) Load a custom X12 definition.



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/x12/parser.rb', line 27

def initialize(file_name, custom_file: false)
  save_definition = @x12_definition if defined? @x12_definition

  if custom_file
    str = File.open(file_name, 'r').read
  else
    # Deal with Microsoft devices
    # get the current working directory
    base_name = File.basename(file_name, '.xml')
    if MS_DEVICES.find { |i| i == base_name }
      file_name = File.join(File.dirname, "#{base_name}_.xml")
    end
    file_location = File.join(File.dirname(__FILE__), '../../misc', file_name)

    # Read and parse the definition
    str = File.open(file_location, 'r').read
  end
  # @dir_name = File.dirname(File.expand_path(file_name)) # to look up other files if needed
  @x12_definition = X12::XMLDefinitions.new(str)

  # Populate fields in all segments found in all the loops
  @x12_definition[X12::Loop].each_pair{ |k, v|
    # puts "Populating definitions for loop #{k}"
    process_loop(v)
  } if @x12_definition[X12::Loop]

  # Merge the newly parsed definition into a saved one, if any.
  if save_definition
    @x12_definition.keys.each { |t|
      save_definition[t] ||= {}
      @x12_definition[t].keys.each { |u|
        save_definition[t][u] = @x12_definition[t][u]
      }
      @x12_definition = save_definition
    }
  end

  # puts PP.pp(self, '')
end

Instance Method Details

#factory(loop_name) ⇒ Object

Make an empty loop to be filled out with information.



79
80
81
82
83
84
# File 'lib/x12/parser.rb', line 79

def factory(loop_name)
  loop = @x12_definition[X12::Loop][loop_name]
  throw Exception.new("Cannot find a definition for loop #{loop_name}") unless loop
  loop = loop.dup
  return loop
end

#parse(loop_name, str) ⇒ Object

Parse a loop of a given name out of a string. Throws an exception if the loop name is not defined.



69
70
71
72
73
74
75
76
# File 'lib/x12/parser.rb', line 69

def parse(loop_name, str)
  loop = @x12_definition[X12::Loop][loop_name]
  # puts "Loops to parse #{@x12_definition[X12::Loop].keys}"
  throw Exception.new("Cannot find a definition for loop #{loop_name}") unless loop
  loop = loop.dup
  loop.parse(str)
  return loop
end