-
Indent with two spaces. This is very nearly universally accepted among Rubyists.
-
Never rescue
Exception
. (See http://technomancy.us/114 for details.) Don't rescueStandardError
(without conditionally re-raising it) unless you have a really good reason. Doing this usually indicates broken code somewhere else. -
CamelCase
for constants,snake_case
for everything else. -
Code isn't finished until it's got tests.
- Keep line length under a hundred unless there's something that you can't break up. (Under 80 is even better, but many consider this an unreasonable burden.) Remember that you can break a line anywhere that it's unambiguous:
Validator.find_validators_for(current_action).
validate(@params) # it may be split in two
- Beware using "and"/"or" instead of &&/|| in assignment since the precedence can be confusing and cause bugs that are difficult to catch.
x = y || z # equivalent to x = (y || z)
x = y or z # equivalent to (x = y) or z
-
Use postfix conditionals only if it's very obvious what's going on. So "return if cond?" is fine since obviously if there's code after the return it must still be reachable. But be wary of more complicated lines.
-
Never use unless with an else.
-
Use {} for single-line blocks and do/end for spanning lines.
-
Regular tests shouldn't hit the network. If you've got tests that need to, split them up into a separate suite.
-
Name predicate methods with a question mark. If you have destructive and non-destructive pairs of methods, the destructive name should end in an exclamation point.
-
Use RDoc for (at least) library-level code. If you have a catch-all options hash argument, document every option that's recognized.
-
Don't use parens on a method call with no arguments.