Ruby & Rails antipatterns
- Use standard routines
- Follow conventions - [unofficial guide (not everything is up to date)] [few basic rails rules]
- Follow naming conventions - [here]
- Think about code ( if you doesn't follow conventions then you must have good reason, but it is not forbidden)
if a == nil or b.nil?
why it is bad: ruby itself eval nil as false, so it is necessary only if variable is boolean so it should look like:
unless a || b # or if !a || !b( I change 'or' to || because we evaluate variables and not workflow )
if a.nil? || a == ""
Use rails method blank? in this case with same result.
a = nil begin a = create_a() rescue Exception => e log.error "Fatal" end if a ... end
Don't rescue exception if you cannot do something usable without it (otherwise you hide errors). Usual thinks where you want rescue exception:
- at top level to report user problem and how he can solve it
- when operation which is done is only optional ( like read cache (recreate it slowly), log (don't log), write progress to user ( user will be more happy if you finish job even if they don't see it) etc...)
- if it is know issue and you want translate exception to better one ( like if reading file fail, check if permission is correct, file exist etc.. and inform user better how to fix it)
Also you should never catch for exception ( unless it is "last catch"). You should catch only what you really want (usually ancestor of RuntimeError or IOError - [ruby exception hierarchy]