I was just shown:
class TheClass
def self.foo
This way you don't risk the missing a change when you rename the
class. You still get the tedious typing though.
However, what does 'class << self' really mean? Why is this one
of the 'obvious' ways to define class methods?
class << obj opens the singleton class of obj. In a class context,
self points to the Class object, therefore in
class A
self # this is A
class << self # same as class << A but needs not be changed if
# if A is renamed
# we're in A's singleton class
end
end
Class methods are in fact class singleton methods (ie. singleton methods
of the object of class Class). You sometimes want to use the class << self
idiom to create attribute accessors for the class, etc:
class A
class << self
attr_accessor :foo
end
end
A.foo = 1
A.foo # => 1
--
_ _
| |__ __ _| |_ ___ _ __ ___ __ _ _ __
| '_ \ / _` | __/ __| '_ ` _ \ / _` | '_ \
| |_) | (_| | |_\__ \ | | | | | (_| | | | |
|_.__/ \__,_|\__|___/_| |_| |_|\__,_|_| |_|
Running Debian GNU/Linux Sid (unstable)
batsman dot geo at yahoo dot com
Make it idiot-proof, and someone will breed a better idiot.
-- Oliver Elphick