Personal blog of Jack Casey.
RSS icon Email icon Home icon
  • Ruby on Rails Tip: .blank? .present? if and unless

    Posted on March 30th, 2011 beetlefeet No comments
    I've long known about the rails convenience method .blank? but only recently learned about its twin: .present?
    Combined with the ability to use "unless" instead of "if" means you can really tweak your conditional statements for readability.
    I like to use "unless" over "if" when I expect the conditional to be false (and the statement to be executed) and I like to use ".present?" over ".blank?" when I don't necessarily expect the attribute or variable to exist.

    Some examples:

    render "no id specified", :status => :unprocessable_entity if params[:id].blank?
    # I don't expect to render the error, I do expect params[:id] to be available

    user.nickname.downcase! unless user.nickname.blank?
    # I do expect to perform the downcase, I do expect nickname to be available

    conditions << {:style => params[:style]} if params[:style].present?
    # I don't assume I'll add the condition, I don't necessarily expect the style parameter to have been passed

    I'm sure some people disagree, but I think those are about as readable as they get. They're also more writable in that you just write what you think rather than having to transform the expression with one or more levels of negation.

    I love how ruby (especially rails) can be so self documenting based on this sorts of almost natural language syntax.

    No TweetBacks yet. (Be the first to Tweet this post)

    Comments are closed.