From: James French Date: 2009-10-03T00:50:55+09:00 Subject: Re: operating on a selection of objects Brilliant. Thanks! > -----Original Message----- > From: Jesús Gabriel y Galán [mailto:jgabrielygalan@gmail.com] > Sent: 02 October 2009 16:28 > To: ruby-talk ML > Subject: Re: operating on a selection of objects > > On Fri, Oct 2, 2009 at 4:54 PM, James French > wrote: > > Hi, > > > > I want to be able to do operations to a selection of objects, > something like this: > > > > class Config > >  attr_accessor :name > > end > > > > class ConfigSelection > > > >  def initialize(*configs) > >    @configs = configs > >  end > > > >  def name=(n) > >    @configs.each{|c| c.name = n} > >  end > > > > end > > > > a = Config.new > > a.name = "a" > > > > b = Config.new > > b.name = "b" > > > > s = ConfigSelection.new(a, b) > > s.name = "s" > > > > > > I was wondering if there might be a more elegant way of doing this, > without having to explicitly duplicate all of Config's attributes in > ConfigSelection? > > This is a way, with the restriction that it only checks instance > methods defined in the class: > > irb(main):015:0> c = Config.new > => # > irb(main):016:0> c.name="test" > => "test" > irb(main):017:0> c2 = Config.new > => # > irb(main):018:0> c2.name = "test2" > => "test2" > > irb(main):041:0> class ConfigSelection > irb(main):042:1> def method_missing meth, *args, &blk > irb(main):043:2> if Config.instance_methods.include? meth.to_s > irb(main):044:3> @configs.each {|c| c.send meth, *args, &blk} > irb(main):045:3> else > irb(main):046:3* super > irb(main):047:3> end > irb(main):048:2> end > irb(main):049:1> end > => nil > irb(main):050:0> csel = ConfigSelection.new c,c2 > => # @name="test">, #]> > irb(main):051:0> csel.name="changed" > => "changed" > irb(main):052:0> csel > => # @name="changed">, #]> > > Hope this gives you some ideas, > > Jesus.