January 26, 2012

Delegate and Decorators

After reading Object on Rails and some blog posts (like Thoughtbot’s one) I started playing with the Ruby’s delegate lib.

Let’s suppose I want to decorate an object, to wrap some instance methods. An simple inheritance from SimpleDelegator would to it

But now, let’s suppose I want to decorate and object and it’s class, to wrap some instance methods AND some class methods.

Like this pseudo code (It won’t work)


Now, I got some tested code, deployed as gem if you want.

Check it out https://github.com/bltavares/delegate-class

I also found it useful to wrap ActiveRecord models and use the rails methods that require it to be an instance of ActievRecord, like #form_for

After playing with DelegateClass, I ended up with this <https://gist.github.com/1680411> code.

It works but I still don’t know if there is a real reason to use it.

But I’m happily playing with delegates. Maybe it is useful to someone (: