Class X12::Parser
In: lib/X12/Parser.rb
Parent: Object

$Id: Parser.rb 35 2008-11-13 18:33:44Z ikk $

Main class for creating X12 parsers and factories.

Methods

Public Class methods

Creates a parser out of a definition

[Source]

    # File lib/X12/Parser.rb, line 33
33:     def initialize(file_name)
34:       str = File.open(file_name, 'r').read
35:       treetop_parser = X12::X12syntaxParser.new
36:       res = treetop_parser.parse(str)
37:       throw Exception.new("Cannot parse X12 definition in #{file_name}") unless res
38:       @x12_definition = res.get
39: 
40:       # Populate fields in all segments found in all the loops
41:       @x12_definition[X12::Loop].each_pair{|k, v|
42:         #puts "Processing loop #{k}"
43:         process_loop(v)
44:       }
45: #       @x12_definition.keys.each{|t|
46: #         puts "**** #{t}"
47:         
48: #         case 
49: #           when t==X12::Segment: @x12_definition[t].each{|i| puts i.inspect; puts i.regexp.source}
50: #           when t==X12::Loop:    @x12_definition[t].each{|i| puts i.inspect.gsub(/\\*\"/, '"') ; puts i.regexp.source}
51: #         else
52: #           puts @x12_definition[t].inspect
53: #         end
54: #         puts "\n\n"
55: #       }
56: 
57:     end

Public Instance methods

Make an empty loop to be filled out with information

[Source]

    # File lib/X12/Parser.rb, line 69
69:     def factory(loop_name)
70:       loop = @x12_definition[X12::Loop][loop_name]
71:       throw Exception.new("Cannot find a definition for loop #{loop_name}") unless loop
72:       loop = loop.dup
73:       return loop
74:     end

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

[Source]

    # File lib/X12/Parser.rb, line 60
60:     def parse(loop_name, str)
61:       loop = @x12_definition[X12::Loop][loop_name]
62:       throw Exception.new("Cannot find a definition for loop #{loop_name}") unless loop
63:       loop = loop.dup
64:       loop.parse(str)
65:       return loop
66:     end

Recursively scan the loop and instantiate fields’ definitions for all its segments

[Source]

    # File lib/X12/Parser.rb, line 78
78:     def process_loop(loop)
79:       loop.nodes.each{|i|
80:         case i
81:           when X12::Loop: process_loop(i)
82:           when X12::Segment: process_segment(i)
83:           else return
84:         end
85:       }
86:     end

Instantiate segment‘s fields as previously defined

[Source]

    # File lib/X12/Parser.rb, line 89
89:     def process_segment(segment)
90:       segment_definition = @x12_definition[X12::Segment][segment.name]
91:       return unless segment_definition
92:       segment_definition.nodes.each_index{|i|
93:         segment.nodes[i] = segment_definition.nodes[i] 
94:       }
95:     end