Class: X12::Parser

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

Overview

$Id: Parser.rb 89 2009-05-13 19:36:20Z ikk $

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']

Instance Method Summary collapse

Constructor Details

#initialize(file_name) ⇒ Parser

Creates a parser out of a definition



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
66
67
68
69
70
71
72
73
# File 'lib/x12/parser.rb', line 38

def initialize(file_name)
  save_definition = @x12_definition
  $count = 0

  # 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
  #@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



87
88
89
90
91
92
# File 'lib/x12/parser.rb', line 87

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, yield_loop_name = nil, &block) ⇒ Object

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



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

def parse(loop_name, str, yield_loop_name=nil, &block)
  raise "Must provide a block if you specify a yield_loop_name" if yield_loop_name && !block
  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, yield_loop_name, block)
  return loop
end