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

(Tuis.) #1

20 | Chapter 1: Foundational Techniques


Class variables can be somewhat confusing to use. They are shared all the way down
the inheritance hierarchy, so subclasses that modify a class variable will modify the
parent’s class variable as well.


>> class A; @@x = 3 end
=> 3
>> class B < A; @@x = 4 end
=> 4
>> class A; @@x end
=> 4

This may be useful, but it may also be confusing. Generally, you either want class
instance variables—which are independent of the inheritance hierarchy—or the
class inheritable attributes provided by ActiveSupport, which propagate values in
a controlled, well-defined manner.


Blocks, Methods, and Procs


One powerful feature of Ruby is the ability to work with pieces of code as objects.
There are three classes that come into play, as follows:


Proc
AProcrepresents a code block: a piece of code that can be called with argu-
ments and has a return value.


UnboundMethod
This is similar to aProc; it represents an instance method of a particular class.
(Remember that class methods are instance methods of a class object, so
UnboundMethods can represent class methods, too.) AnUnboundMethodmust be
bound to a class before it can be invoked.


Method
Methodobjects are UnboundMethods that have been bound to an object with
UnboundMethod#bind. Alternatively, they can be obtained withObject#method.


Let’s examine some ways to getProcandMethodobjects. We’ll use theFixnum#+
method as an example. We usually invoke it using the dyadic syntax:


3 + 5 # => 8

However, it can be invoked as an instance method of aFixnumobject, like any other
instance method:


3.+(5) # => 8

We can use theObject#methodmethod to get an object representing this instance
method. The method will be bound to the object thatmethod was called on, 3.


add_3 = 3.method(:+)
add_3 # => #<Method: Fixnum#+>

This method can be converted to aProc, or called directly with arguments:

Free download pdf