Which of these is better Ruby code formatting style, and why?
Option A:
def load_business
@business ||= if params[:badge_uuid]
# some code
else
# some other code
end
end
Option B:
def load_business
@business ||= if params[:badge_uuid]
# some code
else
# some other code
end
end
It's a subjective question, so we can only give (hopefully reasoned) opinions. I always use option A. My rationale:
The block of code is opened and closed at the same indentation-level, that creates a "visual cohesion".
If the variable name changes its size, you don't need to edit anything (some text editors handle this automatically, though).
You create a "hole" in the source code. The larger the variable name, the bigger the hole. IMO this is visually annoying. Also, you have less space available till reaching some reasonable 80/100-char limit.
I use this style when writing multi-line hashes/arrays/... (note the comma also in the last element so we can re-order them easily and in diff-friendly way):
hash = {
:a => 1,
:b => 2,
}
array = [
:a,
:b,
]
I would use Option A.
Here is some ActiveRecord code that is also that way.
https://github.com/rails/rails/blob/master/activerecord/lib/active_record/associations/has_many_association.rb#L35
EDIT:
This is a pretty opinionated question, there likely is no right answer. Because of that no matter how you do it as long as it's not just ugly code people probably won't hold it against you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With