Dienstag, 25. Dezember 2012

The AOP in Ruby

Needless to say Ruby stands for readable codes, prototyping mixins and other paradigms. In this post I present the paradigma of aspect oriented programming in Ruby (short AOP). What is it good for?
Say you included a cool gem, but it contains one feature, you have to enhance to fulfill your requirement. You have got two options:
  1. copy the code of the feature and overwrite the method with the enriched logic
  2. AOP
The drawback with the first option is the copy & overwrite part. Overwriting means your application will never benefit from bugfixes and enhancements of the original code.
That's why you better go with the aspect oriented paradigma, recycling the original code and injecting new logic.
Fortunately Ruby as a great metaprogramming language offers an easy exposure to AOP. Easy as follows.
module ActsAsExample
  def feature
    @feature ||= "The original"
    @feature + " feature is oh-some."
  end
end
The ActsAsExample module contains the feature method. Including it into the Example class:
class Example
  include ActsAsExample
end
Using the included feature:
Example.new.feature
returns The original feature is oh-some., as expected. Let's add a new aspect to the Example class:
class Example
  include ActsAsExample
  alias_method :original_feature, :feature

  def feature
    @feature = "My new cool fancy"
    original_feature
  end
end
The use of the same feature method:
Example.new.feature
now returns My new cool fancy feature is oh-some.. The feature method behaves different compared to the original code though the original code was used.
A bugfix of the ActsAsExample module to:
module ActsAsExample
  def feature
    @feature ||= "The original"
    " feature is awesome."
  end
end
will break through to the Example class and again calling the feature:
Example.new.feature
returns the bugfixed My new cool fancy feature is awesome. and please note that no change was made in the copy method of the Example class.
Clean!
Maybe my example is not the best, but I hope it illustrates how easy AOP in Ruby is.
Additionally I point to the Ruby Aquarium framework.
Supported by Ruby 1.9.3

Keine Kommentare:

Kommentar veröffentlichen