--1926193751-1060423635-12545063299363
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-12545063299363
Content-Type: TEXT/PLAIN; charset=ISO-8859-1; format=flowed
Content-Transfer-Encoding: 8BIT

Hi --

On Sat, 3 Oct 2009, Jes Gabriel y Gal wrote:

> On Fri, Oct 2, 2009 at 4:54 PM, James French
> <James.French / naturalmotion.com> wrote:
>> Hi,
>>
>> I want to be able to do operations to a selection of objects, something like this:
>>
>> class Config
>> ttr_accessor :name
>> end
>>
>> class ConfigSelection
>>
>> ef initialize(*configs)
>> configs  onfigs
>> nd
>>
>> ef name)
>> configs.each{|c| c.name  }
>> nd
>>
>> end
>>
>> a  onfig.new
>> a.name  a"
>>
>> b  onfig.new
>> b.name  b"
>>
>> s  onfigSelection.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  onfig.new
> #<Config:0xb7db3f78>
> irb(main):016:0> c.nameest"
> "test"
> irb(main):017:0> c2  onfig.new
> #<Config:0xb7dad038>
> 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  onfigSelection.new c,c2
> #<ConfigSelection:0xb7d9c198 @configs<Config:0xb7db3f78
> @nameest">, #<Config:0xb7dad038 @nameest2">]>
> irb(main):051:0> csel.name
hanged"
> "changed" > irb(main):052:0> csel > #<ConfigSelection:0xb7d9c198 @configs<Config:0xb7db3f78 > @name
hanged">, #<Config:0xb7dad038 @name
hanged">]>
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-12545063299363-- --1926193751-1060423635-12545063299363--