Say you included a cool gem, but it contains one feature, you have to enhance to fulfill your requirement. You have got two options:
- copy the code of the feature and overwrite the method with the enriched logic
- AOP
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 endThe ActsAsExample module contains the feature method. Including it into the Example class:
class Example include ActsAsExample endUsing the included feature:
Example.new.featurereturns 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 endThe use of the same feature method:
Example.new.featurenow 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 endwill break through to the Example class and again calling the feature:
Example.new.featurereturns 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