Jackbox allows the scaling of Decorators onto the entire object. Traditionally this has been a problem for Ruby. There have been some partial solutions published by different authors, but they all fall short of the
true GOF standard, posing some problems for their effective use and implementation. Here are a couple of references on the subject matter for your review:
Evaluating Alternative Decorator Implementations and
Decorator Pattern in Ruby.
But, with Jackbox we overcome these problems and give a new spin to this design pattern with Ruby. The Injector metaphor is the key, take a look at this code:
# our class (can be anything..., think html rendering, or string processing)
class Coffee
def cost
1.50
end
end
# our decorators
trait :milk do # first decorator
def cost
super() + 0.30
end
end
trait :vanilla do # second decorator
def cost
super() + 0.15
end
end
# the coffee
cup = Coffee.new.enrich(milk, vanilla, vanilla)
# the list can go on....
# our tests
cup.cost.should == 2.10
cup.injectors.sym_list.should == [:milk, :vanilla, :vanilla]
# coffee is coffee
cup.should be_instance_of(Coffee)
|
Multiple applications of the same decorator are a cinch, just add them to the end of the list. Class identity remains untouched, a coffee is a coffee after all. Removing a decorator can be done by calling #eject or sending Injector Directives, and most of all the code is clean and concise. For more on Injectors and their function see the main page or the project rspec files.
No comments:
Post a Comment