From: Logan Capaldo Date: 2006-09-04T12:32:24+09:00 Subject: Re: Exploring Metaprogramming On Sep 3, 2006, at 10:39 PM, Michael Gorsuch wrote: > > What if I want to build a second method called 'command'? It > should place > the argument in an array that can be referenced later. It will > need to also > build an initialize method for my class, but one of them will have > to be > overwritten. > > Does anyone have any smart ways to combine or chain these two > initialize > methods together? > > I ultimately want to do something like this: > > class Dragon < Creature > traits :life > life 100 > > command :fly > > def fly > puts "I am flying..." > end > > end > > After an instance is created, it will contain the instance variable > 'commands', which is an array holding the symbol 'fly'. > > Does anyone have any ideas? In the end, I'd be adding more and > more of > these commands to my DSL. This is a DSL, right? ;-) Sorry I seem to have under estimated what you wanted. try this instead: % cat dragon.rb class Creature def self.command(cmd) old_initialize = instance_method(:initialize) define_method(:initialize) do |*args| @commands ||= [] @commands |= [cmd] old_initialize.bind(self).call(*args) end end def commands @commands ||= [] end end class Dragon < Creature command :fly def fly puts "I'm flying" end command :breathe_fire def breathe_fire puts "I'm breathing fire!" end end dragon = Dragon.new p dragon.commands % ruby dragon.rb [:breathe_fire, :fly]