Extend self?

I am a newbie to Ruby. I've found some code in the file dependencies.rb
within Active Support:

module Dependencies
  extend self
...

I would like to ask what does 'extend self' do here? What's purpose? I
didn't found any document mentioning such 'self-extension' case.

Cheers,
Donald

···

--
Posted via http://www.ruby-forum.com/.

That's quite simple, it saves you some typing :slight_smile:

module A
  def a
    p 'a'
  end
end

A.a # doesn't work, because it is not written als def self.a - you
have to include the module in a class and initialize the class to
access it.

module A
  extend self
  def a
    p 'a'
  end
end

A.a
# => 'a'

voila, so now we can access the methods directly, otherwise you would
have to write

module A
  def self.a
    p 'a'
  end
  def a
    p 'a'
  end
end

or similar... makes things a bit simpler - oh, and this is no
scientific point of view of course, just wait for the multitude of
responses that will explain it in detail

( i count on you guys :slight_smile:

···

On 5/27/06, Donald Luo <donaldluo@gmail.com> wrote:

I am a newbie to Ruby. I've found some code in the file dependencies.rb
within Active Support:

module Dependencies
  extend self
...

I would like to ask what does 'extend self' do here? What's purpose? I
didn't found any document mentioning such 'self-extension' case.

Cheers,
Donald

--
Posted via http://www.ruby-forum.com/\.

Really thanks to the quick response, but it seems that the two ways of
definitions are not really equivalent. Just did an experiment.

If I say

module A
  def self.a
    p 'a'
  end
end

class C
  include A
end

C.a

NoMethodError: undefined method `a' for C:Class

c = C.new
c.a

NoMethodError: undefined method `a' for #<C:0x7e478>

While if I changed the definition of module A to

module A
  extend self
  def a
    p 'a'
  end
end

...

C.a

NoMethodError: undefined method `a' for C:Class

c = C.new
c.a

"a"

Anyone can explain this?

Cheers,
Donald

···

--
Posted via http://www.ruby-forum.com/\.

Donald Luo wrote:

module A
  extend self
  def a
    p 'a'
  end
end

class C
  include A
end

C.a

NoMethodError: undefined method `a' for C:Class

Anyone can explain this?

Module functions are not transfered by include by default. You could do this:

class C
   include A
   extend A
end

···

--
http://flgr.0x42.net/