lib/X12/Base.rb in X12-0.1.0 vs lib/X12/Base.rb in X12-1.1.0

- old
+ new

@@ -21,11 +21,11 @@ # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA #++ # module X12 - # $Id: Base.rb 49 2009-03-17 19:46:08Z ikk $ + # $Id: Base.rb 70 2009-03-26 19:25:39Z ikk $ # # Base class for Segment, Composite, and Loop. Contains setable # segment_separator, field_separator, and composite_separator fields. class Base @@ -111,12 +111,15 @@ # Recursively find a sub-element, which also has to be of type Base. def find(e) #puts "Finding [#{e}] in #{self.class} #{name}" case self when X12::Loop + # Breadth first + res = nodes.find{|i| e==i.name } + return res if res + # Depth now nodes.each{|i| - return i if e==i.name res = i.find(e) if i.kind_of?(X12::Loop) return res unless res.nil? or EMPTY==res # otherwise keep looping } when X12::Segment return find_field(e).to_s @@ -141,10 +144,12 @@ end # The main method implementing Ruby-like access methods for nested elements def method_missing(meth, *args, &block) str = meth.id2name + str = str[1..str.length] if str =~ /^_\d+$/ # to avoid pure number names like 270, 997, etc. + #puts "Missing #{str}" if str =~ /=$/ # Assignment str.chop! #puts str case self @@ -168,9 +173,18 @@ def [](*args) #puts "squares #{args.inspect}" return self.to_a[args[0]] || EMPTY end + # Yields to accompanying block passing self as a parameter. + def with(&block) + if block_given? + yield self + else + throw Exception.new("Method 'with' requires a block.") + end + end + # Returns number of repeats def size return self.to_a.size end