-----Original Message-----
From: Jes=FAs Gabriel y Gal=E1n [mailto:
[email protected]]
Sent: 02 October 2009 16:28
To: ruby-talk ML
Subject: Re: operating on a selection of objects
=20
Hi,
I want to be able to do operations to a selection of objects, something like this:
class Config
=A0attr_accessor :name
end
class ConfigSelection
=A0def initialize(*configs)
=A0 =A0@configs =3D configs
=A0end
=A0def name=3D(n)
=A0
[email protected]{|c| c.name =3D n}
=A0end
end
a =3D Config.new
a.name =3D "a"
b =3D Config.new
b.name =3D "b"
s =3D ConfigSelection.new(a, b)
s.name =3D "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?
=20
This is a way, with the restriction that it only checks instance
methods defined in the class:
=20
irb(main):015:0> c =3D Config.new
=3D> #<Config:0xb7db3f78>
irb(main):016:0> c.name=3D"test"
=3D> "test"
irb(main):017:0> c2 =3D Config.new
=3D> #<Config:0xb7dad038>
irb(main):018:0> c2.name =3D "test2"
=3D> "test2"
=20
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
=3D> nil
irb(main):050:0> csel =3D ConfigSelection.new c,c2
=3D> #<ConfigSelection:0xb7d9c198 @configs=3D[#<Config:0xb7db3f78
@name=3D"test">, #<Config:0xb7dad038 @name=3D"test2">]>
irb(main):051:0> csel.name=3D"changed"
=3D> "changed"
irb(main):052:0> csel
=3D> #<ConfigSelection:0xb7d9c198 @configs=3D[#<Config:0xb7db3f78
@name=3D"changed">, #<Config:0xb7dad038 @name=3D"changed">]>
=20
Hope this gives you some ideas,
=20
Jesus.