From: "David A. Black" Date: 2009-10-03T02:59:04+09:00 Subject: Re: operating on a selection of objects --1926193751-1060423635-1254506329=:19363 Content-Type: MULTIPART/MIXED; BOUNDARY="1926193751-1060423635-1254506329=:19363" This message is in MIME format. The first part should be readable text, while the remaining parts are likely unreadable without MIME-aware tools. --1926193751-1060423635-1254506329=:19363 Content-Type: TEXT/PLAIN; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 8BIT Hi -- On Sat, 3 Oct 2009, Jes�s Gabriel y Gal�n wrote: > 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">, #]> While it's probably not likely, it is possible that you'll get some false positives there. For example, if Config includes a module with a method that ConfigSelection doesn't have, and then you call that method on a ConfigSelection instance.... Like I said, not likely :-) But it could happen. It's probably best at least to toss in a 'false': if Config.instance_methods(false).... (but also beware that in 1.9, the *methods methods return arrays of symbols). David -- David A. Black, Director Ruby Power and Light, LLC (http://www.rubypal.com) Ruby/Rails training, consulting, mentoring, code review Book: The Well-Grounded Rubyist (http://www.manning.com/black2) --1926193751-1060423635-1254506329=:19363-- --1926193751-1060423635-1254506329=:19363--