Hi --

On Mon, 23 Oct 2006, Luc Juggery wrote:

> The thing I do not really understand is the instance_eval and
> class_eval in the self.traits method.
> It seems that metaclass.instance_eval define_method create a Class
> method in the Creature class. Creating a method in the singleton class
> of a Class class always define a Class method?

Yes.

> can the Singleton class can also be used to create an instance
> method of Creature ?

No, those methods will not be visible to instances of Creature.  Think
of it from the object's perspective.  Every object has a method
look-up path, consisting of classes (including its singleton class)
and modules.  The whole point of a singleton class is that it lies on
the look-up path of only one object.  (There's one exception to this;
see below.)  Therefore, if the class object Creature has a method in
its singleton class, and you do: c = Creature.new, c is a different
object from Creature, and the methods defined in Creature's singleton
class are not visible to it.

The exception is subclasses.  If you subclass Creature, the new class
will be able to call Creature's singleton methods.  It's a special
arrangement so that class methods can be inherited.

> Is the way presented in this example is what is commonly done to
> dynamically define Class and instance method of a Class or are there
> any other possible syntaxes ?

You can use eval("def #{method_name}...") but it's fragile and
inadvisable.

> The self.traits method also define accessors methods: attr_accessor
> *arr, how come this is not done within a define_method statement?

The attr_* family of methods are basically wrappers around method
definitions.  They're just shorter and more convenient, but the effect
is the same.


David

-- 
                   David A. Black | dblack / wobblini.net
Author of "Ruby for Rails"   [1] | Ruby/Rails training & consultancy [3]
DABlog (DAB's Weblog)        [2] | Co-director, Ruby Central, Inc.   [4]
[1] http://www.manning.com/black | [3] http://www.rubypowerandlight.com
[2] http://dablog.rubypal.com    | [4] http://www.rubycentral.org