How much do we pay attention to the names of models and methods? If you are a native English speaker, it might have been easy for you to get a sense of it. To be honest with you, it wasn't too easy for me till I understood there are some conventions, as English is my second language. In this article, I will introduce those conventions that apply to Ruby and Rails.
Model names should be noun
# Bad
class Pay
end
# Good
class Payment
end
This is because if we assign instances to a variable, the name of the variable will be weird.
pay = Pay.new
pays = Pay.all # pays??????
If there are more than two words for the model name, use adjective + noun or noun + noun.
# Bad
class AttachFile
# This is confusing because it looks like a method name.
end
# Good
class AttachedFile
end
# Good
class UserSegment
end
A method which executes something should be verb or verb + noun
# Change user's status to "active"
# Bad
user.active
# Good
user.activate
# Send an email to the user
# Bad
user.email
# Good
user.send_email
Be careful using uncountable nouns in Rails
In Rails, there is a convention for using singular/plural forms when you define something like routes and models. Some uncountable nouns like "information" are accepted, but you should be really careful when using uncountable nouns since it can cause not just confusion but errors.
If you are not sure whether the word you want to use is uncountable or not, or if you don't know what its plural form is, there is a very non-native friendly method in Rails. .pluralize
returns the plural form of the given string.
# console
"person".pluralize
=> "people"
"sheep".pluralize
=> "sheep"
"octopus".pluralize
=> "octopi" # Did you know this?!
"the blue mailman".pluralize
=> "the blue mailmen"
'CamelOctopus'.pluralize
=> "CamelOctopi"
# You can set the optional parameter for the count
"apple".pluralize(1)
=> "apple"
"apple".pluralize(2)
=> "apples"
Besides those conventions, it is always a good idea to get someone to review your code. It helps you get a better sense of naming models and methods.
Top comments (0)