From: Robert Klemme Date: 2005-10-28T00:42:03+09:00 Subject: Re: overriding #inspect Eric Mahurin wrote: > --- Robert Klemme wrote: > >> Eric Mahurin wrote: >>> --- Robert Klemme wrote: >>> >>>>>>>> On 10/26/05, Eric Mahurin >>>> wrote: >>>>>>>>> Anybody know what the best way to override inspect where you >>>>>>>>> may have a recursive data structure? >>> >>> >>>> .... which reminds me of an RCR I've been wanting to submit >>>> for quite some >>>> time now: >>>> http://rcrchive.net/rcr/show/323 >>>> >>>> This could help here, too. >>>> >>>> Kind regards >>>> >>>> robert >>> >>> Could you describe how this could be used to override #inspect? >>> Or any other example? I think a ruby implementation RCR would >>> go a long way. >> >> Without going into the details: >> >> def inspect >> s = "" >> traverse(self) do |obj| >> s << "(" if Enumerable === obj >> s << do_whatever(obj) >> s << ")" if Enumerable === obj >> end >> s >> end >> >> It might even be interesting to have a second parameter which >> indicates >> the distance from the start object. That way indentation >> would be easy >> and maybe it can be used for other stuff as well. Just an >> idea. > > But this wouldn't allow child objects to use their own > #inspect, would it? Yes, but do_whatever() can handle this (for example call a method on the instance)... > I think the best solution for changing the #inspect behavior of > a class would be to have #inspect deal with recursion issues > and call another method (or two) to generate the strings: > > def inspect > # several ways to accomplish this thread-local instance var > if inspect_thread_local_instance_variable > inspect_stop > else > begin > inspect_thread_local_instance_variable = true > inspect_contents > ensure > inspect_thread_local_instance_variable = false > end > end > def inspect_stop > .. generate an inspect string w/o children ("..." instead) > end Did you mean "inspect_contents" here: > def inspect_children > .. generate an inspect string w/ children > end > > > With this infrastructure, you could easily change the #inspect > behavior by overriding #inspect_stop and/or #inspect_children. > No need to worry about recursion. I would add inspect_start and invoke each method with a string that they can append to but otherwise, yes. Kind regards robert