Pretty Little Ruby

Tuesday, October 2 2011 ruby

One thing I really like about Ruby is the ability to refactor to one line. Note that this isn't some spartan thing I have going, nor some geek-macho :) "look what I can do". Instead, I find it a lot more readable. Here's why...

My Little Pretty

Well-written Ruby is concise and incredibly readable. This is not limited to Ruby, of course - it's true for all languages - but "prettiness" isn't considered a mark of good code. It is for Ruby, and I for one kind of like it.

For instance - let's say you have an Observer in your Rails app that watches Transactions, and when a new Transaction is created, you want some things to happen (sort of like Events in C#).
You might have some code like this:

def aftercreate(trans)
#is this a payment? if trans.kind "capture" || trans.kind "subscription-payment" || trans.kind "coupon" handle
payment(trans) elsif trans.kind "refund" handle_refund(trans) else raise "Don't know what kind of transaction this is!" end end

This code works - but as they say it looks like it's been written by a .NET programmer :). Which indeed it was! But it lacks some idiomatic "ruby-ness". Let's fix that.

One Liners

First, let's refactor out that if statement and use the comment as a guide for our new method name. I'll stick a method on Transaction and call it "is_payment?" (note the question mark) - I'll do the same for refund - this kind of thing should be tucked into our model anyway...

def ispayment?
kind "capture" || kind "subscription-payment" || kind "coupon" end
def is
kind "refund" end

Much nicer. Now I can rewrite this whole thing:

This code has been updated per comments from Peter Cooper...

handlepayment and return if trans.ispayment?
handlerefund and return if trans.isrefund?
raise "Don't know what kind of transaction this is!"

Note, that I could make this

all one line

if I chose:

handlepayment if trans.ispayment? or handlerefund if trans.isrefund? or raise "Don't know what kind of transaction this is!"

In this case - I think 3 "ors" in a single sentence is a bit much to read. To me, each of these lines has a phantom comma after them and I wouldn't feel comfortable giving someone instructions in plain language by using a bunch of "ors".

Or maybe I would.

Does This Really Matter?

No, not really. Well the first refactor matters but the rest of it... it's all "style". Unless, of course, you think about the poor slob who is going to inherit this code. By making this

as readable as possible,

which is always nice.

Well, it's more than nice - it's our job isn't it :).