Ruby: extend self
It is a convenient way to make instance methods into class methods. But you can also use it as a more efficient singleton.
For me it always helps to think of extend
as include
inside the singleton class (also known as meta or eigen class).
You probably know that methods defined inside the singleton class are basically class methods:
module A
class << self
def x
puts 'x'
end
end
end
A.x #=> 'x'
Now that we know that, extend
will include
the methods in the module inside the singleton class and thus expose them as class methods:
module A
class << self
include A
def x
puts 'x'
end
end
def y
puts 'y'
end
end
A.x #=> 'x'
A.y #=> 'y'
In a module, self is the module class itself. So for example
puts self
will return Rake so,
extend self
basically makes the instance methods defined in Rake available to it, so you can do
Rake.run_tests