Wednesday, September 19, 2007

Evil Ruby in Practice

Evil Ruby is more than just a hacker's wet dream with a rock-n-roll name. When I first learned of it I presumed there was little practical use for its dark magic - yet I find myself now utilizing it more than expected.

One of the radder (more rad?) incantations of Evil is as_module. This innocuously sounding method attached to Class is insidious enough to make Satan blush. In short - it converts a Class to a Module. Why? Imagine the glory of using a class as a mixin - as seen in the little configuration system below (via include Array.as_module):

I want CompositeConf to contain all of the Array methods, yet want the inheritance hierarchy to specialize from Conf (that way a CompositeConf can be used like any other configuration - without needing to know it is a composite).

Let us play in the resulting blood bath by creating a composite configuration containing a few Configs.

Just to ensure it is working as planned - ask for the value of the key :water.

Which should output:
But so what? We want to use Array's methods. So - let's add a nil into the CompositeConf and then compact it (Array.compact removes nil values from an array).

The first output is the CompositeConf containing the nil - the second is the compacted version.
[#<Conf:0x1050158 @hash={:sky=>"blue", :water=>"wet"}>, #<Conf:0x105011c @hash={:women=>"???"}>, nil]
[#<Conf:0x1050158 @hash={:sky=>"blue", :water=>"wet"}>, #<Conf:0x105011c @hash={:women=>"???"}>]
If that's not evil, well, then maybe I'm in the wrong industry - perhaps I should make a career change right now.

1 comment:

Anonymous said...

Evil ha! You know 'nothing', try reading some Maquis De Sade, as a taster. Also have a look at "The Corporation" (book and film).