While I was following the #railsconf thread on Twitter, I heard some talking about method decorators with Ruby. I’ve always wondered if there was a way to emulate the Attribute we have in .NET.
Turns out it is possible (and with added value!). Using the method_decorators gem allow precisely that functionnality with some extras.
Defining a decorator
1 2 3 4 5 | |
This decorator actually does nothing, since we call the original method with supplied arguments and block (if provided).
Using the decorator
1 2 3 4 5 6 7 8 | |
We can now do something before and after the call to do_something and even modify the return value.
A practical example
I’ve had this little problem in .NET where I wanted to profile different method calls to see how much time they took to execute and send back the result via MiniProfiler. For this, I wanted only to add an attribute to those methods. The only way I have found that possible without the use of an advanced profiling tool was to use PostSharp and it’s injecting code feature. The Attribute functionnality does not offer any kind of before and after hook on execution.
A custom implementation would look like this.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | |
PostSharp will inject the OnEntry and OnExit code at the start and at the end of the “decorated” method. By default, there is no way to achieve that easily.
With Ruby, the method_decorators gem and a custom profiler, it would look like this.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | |
How nice is that?