Prev | Current Page 54 | Next

Brad Ediger

"Advanced Rails"


For whatever reason, Ruby AOPtechniques have not taken off. We will now introduce
the standard way to deal with separation of concerns in Ruby.
Method chaining
The standard Ruby solution to this problem is method 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 calling super in an inherited overriden method). The effect is that a feature
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
34 | Chapter 1: Foundational Techniques
There is a standard Ruby idiom for chaining methods. Assume we have some library
code that grabs a Person object from across the network:
class Person
def refresh
# (get data from server)
end
end
This operation takes quite a while, and we would like to time it and log the results.
Leveraging Ruby??™s open classes, we can just open up the Person class again and
monkeypatch the logging code into refresh:
class Person
def refresh_with_timing
start_time = Time.now.to_f
retval = refresh_without_timing
end_time = Time.


Pages:
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66