Can anyone shed some light!

20 views
Skip to first unread message

Kike Luka

unread,
Dec 23, 2014, 6:58:02 PM12/23/14
to rubyonra...@googlegroups.com
Can anyone shed some light on this?

https://github.com/LouHenryAlvarez/jackbox

It looks like some sort of abstraction. But I a having trouble
understanding how this works. Also the following code doesn't make any
sense to me.

<pre>

Furhtermore, these decorators can be re-applied multiple times to the
same receiver:

cup = Coffee.new.enrich(milk).enrich(sprinkles).enrich(sprinkles)
# or even..
cup = Coffee.new.enrich milk, sprinkles, sprinkles

cup.cost.should == 2.10
cup.should be_instance_of(Coffee)
cup.injectors.should == [:milk, :sprinkles, :sprinkles

</pre>

Isn't this sort of thing already possible already. Can someone explain?


Thanks,

Kike

--
Posted via http://www.ruby-forum.com/.

Lou Henry

unread,
Dec 25, 2014, 2:44:39 AM12/25/14
to rubyonra...@googlegroups.com
Yes, what you are looking at here is a code sample of what is possible
with Jackbox closures. You see normally decorators in ruby either suffer
from class identity loss or limit the times they can be applied to an
object to 1(one) time.

Here a a couple of articles on that:

http://nithinbekal.com/posts/ruby-decorators/

http://robots.thoughtbot.com/evaluating-alternative-decorator-implementations-in


So with our closures you can apply the same pattern to an object over
and over,

cup = Coffee.new.enrich milk, sprinkles, sprinkles

but the instance remains being what it is.

cup.should be_instance_of(Coffee)

What's more you can have the class introspect on the decorators it
possesses.

cup.injectors.should == [:milk, :sprinkles, :sprinkles ]

Furthermore you can add new facets to your decorators:

user_input = 'extra red sprinkles'
sprinkles do
define_method :appearance do
user_input
end
end

cup.enrich(sprinkles)
cup.appearance.should == 'extra red sprinkles'
cup.cost.should == 2.25

And then latter:

user_input = 'cold milk'
milk do
define_method :temp do
user_input.split.first
end
end

cup.enrich milk
cup.temp.should == 'cold'
cup.cost.should == 2.55

Decorators are useful in graphical environments including HTML, in steam
processing, command processors to name a few.


Thank you, kindly.

lha
Reply all
Reply to author
Forward
0 new messages