Ruby 2.0.0 - named parameters
Recently I changed to Ruby 2.0.0 in a project I am working on. I think I am going to share some things that I found specially attractive when I find them in a series of small posts (this might be the only one though)
In the few weeks I have been playing around with Ruby 2.0.0 I really have come to love named parameters. You know them already from other languages (in Smalltalk and Objective-C, for example, you find this type of function calls) and I always have loved them for the clarity in the language they give. It is much easier to compose a meaningful sentence and make the messages you send across much more explicit.
There is one thing about the Ruby’s implementation of the named parameters that I am really fond of though. Let me show you first how the method definition looks now:
What does all this mean in practical terms?
Imagine you have a Use Case you are working on, it shows a project for a user in a project management tool. This method could look like this:
As you can see we are looking up the user and the project by their names and then passing them to a presenter wich will render the project board; a simple task.
We can argue that the user and the project should not really be looked up in the method body (they are needed for the presenter to render the page, but are a possible violation of the Single Responsibility Principle, if we are being purists about it) as the method is only in charge of showing the project (as it’s name indicates).
The beauty comes from what we can do now with it due the new flexibility Ruby 2.0.0 gives us.
And suddenly our method follows the Single Responsibility Principle again!
Obviously all this can be overdone and I would recommend you to explore the possibilities before you start messing up your production codebase.
Remember it is all about making your code clearer and cleaner!
Update!
As Chad mentioned in the gist, something similar as I show above can be done in Ruby 1.8.x already. I was to eager to get the blogpost out and I forgot to add a little spice to the method so that it would become cleaner and more readable:
If you look at this now from the clients point of view it actually becomes a nifty method call:
Thank you for pointing it out Chad!


