From: Robert Dober Date: 2007-04-19T20:18:52+09:00 Subject: Re: to_s mixin/reflection/newbie stuff On 4/18/07, hemant wrote: > On 4/19/07, hemant wrote: > > On 4/19/07, hemant wrote: > > > On 4/19/07, Kris Helenek wrote: > > > > Thanks Hemant! I still have trouble seeing things as methods without > > > > the parentheses(); but it makes perfect sense now. And i wrote a nice > > > > little module to duplicate what is often done to create good debug > > > > output in hibernate (j2ee world): > > > > > > > > module ReflectionToString > > > > def to_s > > > > str = self.class.name + "[" > > > > for attribute in self.attributes > > > > str += attribute[0].to_s + ": " + attribute[1].to_s + ", " > > > > end > > > > str += "]" > > > > str > > > > end > > > > end > > > > > > > > Someone could probably clean it up a bit but its just a first pass... > > > > > > def to_s > > > str = "#{self.class} [" > > > @attributes.each {|x| str << "#{attribute[0]} : #{attribute[1]} , " } > > > str << "]" > > > end > > > > > > No need to return str, because last statement evaluated is returned. > > > > > > > > > > > I have a Rails specific question (i know this is kinda the wrong forum, > > > > but I'm already here..) Where is the appropriate place to store this > > > > module? In the helper or model folder? lib? A new folder? Don't know the > > > > conventions yet and I haven't seen anything about utility classes yet... > > > > thanks again. > > > > > > > > > > #{RAILS_ROOT}/lib is the appropriate place, although when it grows a > > > little more bigger and may be reusable, its good idea to create a > > > plugin. > > > > > > > > > Oops, replace "attribute" with x in the iterator, please. > > > > > Also, your method is a bit buggy and hence mine is too, it value > returned by to_s will have a "," at the end. > > so a better approach would be: > > def to_s > str = "#{self.class} [" > str << @attributes.map {|key,value| "#{key} : #{value}"}.join(',') > str << "]" > end > > Is inspect not a better choice? Maybe the following code snippet proves helpfull: 430/6 > irb irb(main):001:0> class A irb(main):002:1> attr_accessor :a irb(main):003:1> end => nil irb(main):004:0> class B irb(main):005:1> attr_accessor :b irb(main):006:1> end => nil irb(main):007:0> a = A.new => # irb(main):008:0> b = B.new => # irb(main):009:0> b.b = 0x2a => 42 irb(main):010:0> a.a=b => # irb(main):011:0> a.inspect => "#>" irb(main):012:0> HTH Robert -- You see things; and you say Why? But I dream things that never were; and I say Why not? -- George Bernard Shaw