#-- # This file is part of the X12Parser library that provides tools to # manipulate X12 messages using Ruby native syntax. # # http://x12parser.rubyforge.org # # Copyright (C) 2008 APP Design, Inc. # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA #++ # module X12 # $Id: Parser.rb 35 2008-11-13 18:33:44Z ikk $ # # Main class for creating X12 parsers and factories. class Parser # Creates a parser out of a definition def initialize(file_name) str = File.open(file_name, 'r').read treetop_parser = X12::X12syntaxParser.new res = treetop_parser.parse(str) throw Exception.new("Cannot parse X12 definition in #{file_name}") unless res @x12_definition = res.get # Populate fields in all segments found in all the loops @x12_definition[X12::Loop].each_pair{|k, v| #puts "Processing loop #{k}" process_loop(v) } # @x12_definition.keys.each{|t| # puts "**** #{t}" # case # when t==X12::Segment: @x12_definition[t].each{|i| puts i.inspect; puts i.regexp.source} # when t==X12::Loop: @x12_definition[t].each{|i| puts i.inspect.gsub(/\\*\"/, '"') ; puts i.regexp.source} # else # puts @x12_definition[t].inspect # end # puts "\n\n" # } end # Parse a loop of a given name out of a string. Throws an exception if the loop name is not defined. def parse(loop_name, str) loop = @x12_definition[X12::Loop][loop_name] throw Exception.new("Cannot find a definition for loop #{loop_name}") unless loop loop = loop.dup loop.parse(str) return loop end # parse # Make an empty loop to be filled out with information 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 # factory # Recursively scan the loop and instantiate fields' definitions for all its # segments def process_loop(loop) loop.nodes.each{|i| case i when X12::Loop: process_loop(i) when X12::Segment: process_segment(i) else return end } end # Instantiate segment's fields as previously defined def process_segment(segment) segment_definition = @x12_definition[X12::Segment][segment.name] return unless segment_definition segment_definition.nodes.each_index{|i| segment.nodes[i] = segment_definition.nodes[i] } end end # Parser end