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

(Tuis.) #1

32 | Chapter 1: Foundational Techniques


Another consequence of the functionality being spread around is that it can be diffi-
cult to properly document a method. Because the function of theprocessmethod
can change depending on which code has been loaded, there is no good place to doc-
ument what each of the methods is adding. This problem exists because the actual
identity of theprocess method changes as the methods are chained together.


Adding Functionality to Existing Methods


Because Rails encourages the philosophy of separation of concerns, you often will
have the need to extend the functionality of existing code. Many times you will want
to “patch” a feature onto an existing function without disturbing that function’s
code. Your addition may not be directly related to the function’s original purpose: it
may add authentication, logging, or some other important cross-cutting concern.


We will examine several approaches to the problem of cross-cutting concerns, and
explain the one (method chaining) that has acquired the most momentum in the
Ruby and Rails communities.


Subclassing


In traditional object-oriented programming, a class can be extended by inheriting
from it and changing its data or behavior. This paradigm works for many purposes,
but it has drawbacks:



  • The changes you want to make may be small, in which case setting up a new
    class may be overly complex. Each new class in an inheritance hierarchy adds to
    the mental overhead required to understand the code.

  • You may need to make a series of related changes to several otherwise-unrelated
    classes. Subclassing each one individually would be overkill and would separate
    functionality that should be kept together.

  • The class may already be in use throughout an application, and you want to
    change its behavior globally.

  • You may want to add or remove a feature at runtime, and have it take effect glo-
    bally. (We will explore this technique with a full example later in the chapter.)


In more traditional object-oriented languages, these features would require complex
code. Not only would the code be complex, it would be tightly coupled to either the
existing code or the code that calls it.


Aspect-oriented programming


Aspect-oriented programming(AOP) is one technique that attempts to solve the
issues of cross-cutting concerns. There has been much talk about the applicability of
AO Pto Ruby, since many of the advantages that AO Pprovides can already be

Free download pdf