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

(Tuis.) #1
Metaprogramming Techniques | 33

obtained through metaprogramming. There is a Ruby proposal for cut-based AOP,*
but it may be months or years before this is incorporated.


In cut-based AOP, cuts are sometimes called “transparent subclasses” because they
extend a class’s functionality in a modular way. Cuts act as subclasses but without
the need to instantiate the subclass rather than the parent class.


The Ruby Facets library (facets.rubyforge.org) includes a pure-Ruby cut-based AOP
library.†It has some limitations due to being written purely in Ruby, but the usage is
fairly clean:


class Person
def say_hi
puts "Hello!"
end
end

cut :Tracer < Person do
def say_hi
puts "Before method"
super
puts "After method"
end
end

Person.new.say_hi
# >> Before method
# >> Hello!
# >> After method

Here we see that theTracercut is a transparent subclass: when we create an instance
ofPerson, it is affected byTracerwithout having to know aboutTracer. We can also
changePerson#say_hi without disrupting our cut.


For whatever reason, Ruby AO Ptechniques have not taken off. We will now intro-
duce the standard way to deal with separation of concerns in Ruby.


Method chaining


The standard Ruby solution to this problem ismethod chaining: aliasing an existing
method to a new name and overwriting its old definition with a new body. This new
body usually calls the old method definition by referring to the aliased name (the
equivalent of callingsuperin an inherited overriden method). The effect is that a fea-
ture can be patched around an existing method. Due to Ruby’s open class nature,
features can be added to almost any code from anywhere. Needless to say, this must
be done wisely so as to retain clarity.


*http://wiki.rubygarden.org/Ruby/page/show/AspectOrientedRuby
http://facets.rubyforge.org/api/more/classes/Cut.html

Free download pdf