A guy talking about Rails modularity

There are 2 modules (Bar and Baz) and 2 classes (Foo and Omg) implementing foo method here. Omg class inherits from Foo and additionaly modules Bar and Baz are included in Omg. This code takes advantage of ruby object model. How does it work?

When you instantinate Omg object with Omg.new and call method foo on it, it looks for foo method in current class and its superclasses. So first method that will be actually called is Omg#foo. This method is calling super, so ruby will look for method foo also in Omg’s superclass. At first you could think that it’s Foo, but internally Ruby treats modules as superclasses. That said, the next superclass will be the last included module, which is Baz. After that Bar’s and Foo’s methods will be invoked.

This one of the best patterns I have seen in Ruby so far. Not only it allows to extend objects easily, but also to reuse small chunks of code making the whole thing more modular.

Seems pretty obvious when you look at it (follow the link to see source that the text above is referring to). However, I haven’t structured my own code like this too often. It’s never been mature enough for me to pull things out into modules very often. And of the times I do, it’s mostly because I can’t handle a fat class, and need to pull common things out, but it rarely gets reused.

When it’s early, keep things in a class, before you know the shape of the problem. But when common themes start to appear, pull it out into modules that you can mixin. It’s helpful to have a base class to inherit from so that you are at least guaranteed some base methods and instance variables to use in the mixins.

If it’s not clear what this post is referring to, check out the railscast on the modularity of actioncontroller.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s