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

(Tuis.) #1

14 | Chapter 1: Foundational Techniques


Therefore, it tells us thatobjA’s class isA. This is important to remember: an object’s
class (from Ruby’s perspective) may not match the object pointed to byklass.


Singleton classes are called singleton for a reason: there can only be one singleton
class per object. Therefore, we can refer unambiguously to “objA’s singleton class” or
Class:objA. In our code, we can assume that the singleton class exists; in reality, for
efficiency, Ruby creates it only when we first mention it.


Ruby allows singleton classes to be defined on any object exceptFixnums or symbols.
Fixnums and symbols areimmediate values(for efficiency, they’re stored as themselves in
memory, rather than as a pointer to a data structure). Because they’re stored on their
own, they don’t haveklasspointers, so there’s no way to alter their method lookup
chain.


You can open singleton classes fortrue,false, andnil, but the singleton class
returned will be the same as the object’s class. These values are singleton instances
(the only instances) ofTrueClass,FalseClass, andNilClass, respectively. When you
ask for the singleton class oftrue, you will getTrueClass, as the immediate value
true is the only possible instance of that class. In Ruby:


true.class # => TrueClass
class << true; self; end # => TrueClass
true.class == (class << true; self; end) # => true

Singleton classes of class objects


Here is where it gets complicated. Keep in mind the basic rule of method lookup:
first Ruby follows an object’sklasspointer and searches for methods; then Ruby
keeps followingsuperpointers all the way up the chain until it finds the appropriate
method or reaches the top.


The important thing to remember is thatclasses are objects, too. Just as a plain-old
object can have a singleton class, class objects can also have their own singleton
classes. Those singleton classes, like all other classes, can have methods. Since the
singleton class is accessed through theklasspointer of its owner’s class object,
the singleton class’s instance methods are class methods of the singleton’s owner.


The full set of data structures for the following code is shown in Figure 1-9:


class A
end

ClassAinherits fromObject. TheAclass object is of typeClass.Classinherits from
Module, which inherits fromObject. The methods stored inA’sm_tblare instance
methods ofA. So what happens when we call a class method onA?


A.to_s # => "A"

The same method lookup rules apply, withAas the receiver. (Remember,Ais a constant
that evaluates toA’s class object.) First, Ruby followsA’sklasspointer toClass.Class’s
m_tblis searched for a function namedto_s. Finding none, Ruby followsClass’ssuper
pointer toModule, where theto_s function is found (in native code,rb_mod_to_s).

Free download pdf