Ruby best-practices: Boolean methods

I’ve been reviewing some code recently and have been struck by a few misconceptions about how to handle boolean (true/false) values in ruby. Here’s an example:

[ruby]
def authorise_to_edit_article
if current_user.can_edit_articles and @user_action == ‘edit’
return true
else
return false
end
end
[/ruby]

That will run, but there are a few things wrong with it. First, the method doesn’t do a good enough job of describing itself. Following ruby’s conventions, a method that returns a boolean value usually ends with a question mark. Second, the method name needs to be clearer about who or what is being authorised: maybe current_user_can_edit_article? would be better.

Third, we can slim down this method a lot — and make it much easier for other developers to understand — by removing the if..else code. The method returns true or false, but the logic check used by the if statement will return true or false on its own, so we can just write:

[ruby]
def current_user_can_edit_article?
current_user.can_edit_articles and @user_action == ‘edit’
end
[/ruby]

Much better! That removes 80% of the code, does the same job, is more concise, and is easier to scan.