Search code examples
ruby-on-railsrubyattributesnaming-conventions

Naming conventions for boolean attributes


I want to write code that others easily can understand as well.

Do boolean attributes like hide_email or email_hidden have a convention style?


Solution

  • I think of it like this:

    • A boolean attribute should answer a simple yes/no question.
    • Asking "is?" is a simple way to ask a yes/no question.
    • So a boolean attribute can be though of as a small phrase, containing is. e.g. is <attribute_name> or <attribute_name> is <something>
    • Then just remove the is because Ruby prefers the ? suffix for "is"-style method names (see below for more), leaving you with just <attribute_name> or <attribute_name> <something>.

    So, for your specific case, name your attribute like this:

    • Start with the question "is email hidden?" or "email is hidden?". Which can be represented in code as: is_email_hidden or email_is_hidden.
    • Remove the is and, either way, you're left with email_hidden

    Why?

    • Ruby on Rails defines a "predicate" method (one that ends in a ?) corresponding to all boolean attributes and returns true or false. So, while your attribute is named email_hidden in the database (somewhat stark feeling, no doubt) you can and should reference it as email_hidden? in your code. Both for clarity and because this is the idiomatic Ruby on Rails way.