Jacob Fugal <lukfugl / gmail.com> wrote:

> On 10/27/06, matt neuburg <matt / tidbits.com> wrote:
> > class BigGuy
> >   def setup
> >     @favorites = "bluto"
> >   end
> >   def initialize
> >     setup
> >     p @favorites
> >   end
> >   class MiddleGuy < BigGuy
> >   end
> >   def self.make_subclass(what)
> >     p = Proc.new {@favorites = what}
> >     MiddleGuy.send( :define_method, :setup, p )
> >     return MiddleGuy.clone
> >   end
> > end
> 
> You can do away with the explicit "MiddleGuy" class and the clone
> call, by just creating an anonymous class on each invocation:
> 
>   class BigGuy
>     def setup
>       @favorites = "bluto"
>     end
> 
>     def initialize
>       setup
>       p @favorites
>     end
> 
>     def self.with_favorites(favorites)
>       Class.new(self) do
>         define_method(:setup) do
>           @favorites = favorites
>         end
>       end
>     end
>   end
> 
> And while we're at it, if the only purpose of the on-the-fly class was
> for the subclass to inherit from, why not make the subclass *be* the
> on-the-fly class:
> 
>   LittleGuy = BigGuy.with_favorites('popeye')
>   DevilishGuy = BigGuy.with_favorites(666)
> 
> Then the following code produces the same output as yours above:
> 
>   BigGuy.new #=> "bluto"
>   LittleGuy.new #=> "popeye"
>   BigGuy.new #=> "bluto"
>   DevilishGuy.new #=> 666
>   LittleGuy.new #=> "popeye"

Yeah! I could NOT for the life of me figure out how to make that
anonymous class, and the direct assignment just didn't occur to me.
Thanks - m.


-- 
matt neuburg, phd = matt / tidbits.com, http://www.tidbits.com/matt/
Tiger - http://www.takecontrolbooks.com/tiger-customizing.html
AppleScript - http://www.amazon.com/gp/product/0596102119
Read TidBITS! It's free and smart. http://www.tidbits.com