Quick module include question

module Attributes
  def att(*atts)
    atts.each do |att|
      class_eval %{
        def #{att} val=nil
          val == nil ? @#{att} : @#{att} =
val
        end
      }
    end
  end
end

class World
  extend Attributes
  att :title, :author
end

w = World.new
w.title "Title"
w.author "Author"
p w.title
=> "Title"
p w.author
=> "Author"

···

#####################################################################################
This email has been scanned by MailMarshal, an email content filter.
#####################################################################################

Ahh, that works. I was using "self.att" as opposed to "att" when defining it
in each class. Now plain "att" works when using extend, but not "self.att"
I'm not sure why they switched like that, but at least it works. :slight_smile:

Thanks,
Chris

Selon Chris Eskow <chriseskow@gmail.com>:

Ahh, that works. I was using "self.att" as opposed to "att" when defining it
in each class. Now plain "att" works when using extend, but not "self.att"
I'm not sure why they switched like that, but at least it works. :slight_smile:

That's because "extend" adds the methods defined in the Module *directly* to
your class, as class methods (more exactly as singleton methods of that
particular class), without you having to explicitly indicate it with "self.".
You can see that this way: include adds the methods defined in the module as
instance methods, extend adds them as class methods (at least when it's used in
a class definition).

It's all a matter of scope, and maybe the single difficult thing to understand
about Ruby. But once you understand it, about everything else (including
reflection, metaprogramming, all those high-level things) becomes natural.

As an anecdote, it just happens that the very first time I went into contact
with the Ruby community (on the IRC channel #ruby-lang), nearly two years ago,
my very first question was about the difference between extend and include when
used in a class definition :wink: . It took me a while (and the infinite patience of
the people there at the time) to understand the difference and why it worked
that way, but when I did it was an epiphany :slight_smile: . Suddenly constructions like
this dreaded "class <<self; ...; end" made sense. I feel like I'm passing the
flag at this very moment :wink: (although I'm not doing that very well I must admit
:frowning: ).

···

--
Christophe.

http://rainbow.conlang.free.fr

It takes a straight mind to create a twisted conlang.