From: Felipe Balbi Date: 2011-04-20T06:03:34+09:00 Subject: Re: Making a simple parser Hi, "Jesús Gabriel y Galán" wrote in post #993452: > On Sat, Apr 16, 2011 at 9:52 PM, Felipe Balbi wrote: >> >> @children.each { |child| >> def supported? >> >> input = InputFormat.new(ARGV[0]) >> input.parse >> >> As it turns out, this isn't working because AInputFormat will only >> inherit from InputFormat at the time I actually use it, am I right ? Any >> tips you guys could give me to achieve what I want ? (from several >> possible input formats generate one output format) > > The above doesn't work, because the @children inside the instance > method "parse" is not the same as the @children inside the class > method "self.inherited". You have to give access to the class instance > variable, and then use that one from the parse method (the you will aaa, you're right :-) Good point. > see the next problem): > > class InputFormat > class << self > attr_accessor :children > end > > def initialize(input) > @input = input > end > > def parse > self.class.children.each {|child| child.parse(@input) if > child.supported?(@input)} > end > > def self.inherited(child) > (@children ||= []) << child > end > end > > class AInputFormat < InputFormat > def supported? > # check if we can parse this type of file > end > > def parse > # parse and generate array of hashes in known format > end > end > > ruby-1.8.7-p334 :028 > input = InputFormat.new("test") > => # > ruby-1.8.7-p334 :029 > input.parse > NoMethodError: undefined method `supported?' for AInputFormat:Class > from (irb):11:in `parse' > from (irb):11:in `each' > from (irb):11:in `parse' > from (irb):29 > > The next problem, as you see, is that you are defining instance > methods in the subclasses, but are calling them on the class. Maybe > the methods parse and supported? in the children could be class > methods, or maybe what you store in @children could be an instance of > the class. I'm not instantiating AInputFormat in any part of the code... so making those class methods is the way to go for me :-) Thanks for the tip :-) -- balbi -- Posted via http://www.ruby-forum.com/.