Shortening Code with Ruby and Rails
If something looks ugly in ruby, there’s usually a better way to do it. So was the case this afternoon, in a Rails view template:
You rated this page: Good
All those angle brackets, percent signs plus a mish-mash of HTML and ruby code? Yuk! There must be a better way.
And, as may have been expected, there was. Rescue was delivered via two vectors.
Firstly, there are helpers for use in Rails templates which generate HTML code via a ruby method call. Often these are not useful—where it’s more concise to write the HTML itself—but this is an occasion where they come in very handy for cleaning up some code. Instead of this:
You can write:
I think this makes the code much clearer, as the intent is not obscured by angle brackets.
The second aid was a sudden insight into a feature of ruby I hadn’t thought much about before: everything returns a value. This means, amongst other things, that if-statements return a value: that of the last statement executed in their block. This means the above can be simplified to a single ruby code block!
The appropriate content_tag method is invoked and its return value is passed out as the return value of the if statement to be added to the rendered page. Far fewer brackets and other miscellaneous symbols mean the code is far clearer too.
One last finishing touch:
So clear! A feature of Rails and a feature of Ruby conspire to allow us to produce far more beautiful, obvious code. If your code looks tortuous—maybe you can fix it!