Advanced Rails - Building Industrial-Strength Web Apps in Record Time

(Tuis.) #1

16 | Chapter 1: Foundational Techniques


Theto_smethod has been added toA’s singleton class, orClass:A. Now, whenA.to_s
is called, Ruby will followA’sklasspointer toClass:Aand 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, insideA’s class definition,class <<Acan also be writtenclass <<self, since inside
that definitionAandselfrefer 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.class_method_one; "Class method"; end

def self.class_method_two; "Also a class method"; end

class <<A
def class_method_three; "Still a class method"; end
end

class <<self
def class_method_four; "Yet another class method"; end
end
end

def A.class_method_five
"This works outside of the class definition"
end

class <<A
def A.class_method_six
"You can open the metaclass outside of the class definition"
end
end

Figure 1-10. Singleton class of a class


Class:Object
(virtual)

Class:A
(virtual)

super

Object

A

super

klass

klass
Free download pdf