Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recommended indentation style for Ruby `if` blocks that assign a value to a variable? [closed]

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
like image 315
dan Avatar asked Jan 17 '23 21:01

dan


2 Answers

It's a subjective question, so we can only give (hopefully reasoned) opinions. I always use option A. My rationale:

  1. The block of code is opened and closed at the same indentation-level, that creates a "visual cohesion".

  2. If the variable name changes its size, you don't need to edit anything (some text editors handle this automatically, though).

  3. 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,
]
like image 150
tokland Avatar answered Feb 17 '23 16:02

tokland


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.

like image 28
Azolo Avatar answered Feb 17 '23 15:02

Azolo