Reputation: 34103
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?
Upvotes: 20
Views: 14418
Reputation: 18037
I think of it like this:
is
. e.g. is <attribute_name>
or <attribute_name> is <something>
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:
is_email_hidden
or email_is_hidden
.is
and, either way, you're left with email_hidden
Why?
?
) 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.Upvotes: 35
Reputation: 3723
Taking these two examples of names you gave:
hide_email
would be a good name for a method performing such a task, a method that executes all the procedures to hide an email in the scope of your system. But it would never be a good name for a boolean method returning the state of an e-mail.email_hidden?
, with a question mark (?) at the end, would be the correct name for a boolean method indicating if the e-mail is hidden or not.Always consider Ruby conventions if you really want to write good code. They will help you even when thinking about the processes in your system.
Upvotes: 3
Reputation: 2965
The ruby code smeels said that all boolean methods should finish with ?
On active record you could see
User.valid?
Or in ruby you could find
[].nil?
[].empty?
If you want to know about Ruby's conventions read this
http://blogs.visoftinc.com/2010/04/12/ruby-beauty-method-naming-conventions/
Upvotes: 2
Reputation: 11823
That would be email_hidden?
. It is what Ruby community got used to.
Please note the ?
at the end.
Upvotes: 2