Prev | Current Page 29 | Next

Brad Ediger

"Advanced Rails"

Indeed, this works:
class A; end
# from Module#to_s
A.to_s # => "A"
class Class
def to_s; "Class#to_s"; end
end
A.to_s # => "Class#to_s"
That is an interesting trick, but it is of very limited utility. Usually we want to define
unique class methods on each class. This is where singleton classes of class objects
are used. To open up a singleton class on a class, simply pass the class??™s name as the
object to the singleton class notation:
class A; end
class B; end
class <def to_s; "Class A"; end
end
A.to_s # => "Class A"
B.to_s # => "B"
The resulting data structures are shown in Figure 1-10. Class B is omitted for brevity.
Figure 1-9. Full set of data structures for a single class
Object
Module
super
Class
super
A klass
super
16 | Chapter 1: Foundational Techniques
The to_s method has been added to A??™s singleton class, or Class:A. Now, when A.to_s
is called, Ruby will follow A??™s klass pointer to Class:A and invoke the appropriate
method there.
There is one more wrinkle in method definition. In a class or module definition, self
always refers to the class or module object:
class A
self # => A
end
So, inside A??™s class definition, class <that definition A and self refer to the same object. This idiom is used everywhere in
Rails to define class methods. This example shows all of the ways to define class
methods:
class A
def A.


Pages:
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41