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

Which one is the best 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 
+4
source share
3 answers

This is a subjective question, so we can only give (hopefully well-reasoned) opinions. I always use option A. My explanation:

  • A block of code opens and closes at the same level of indentation, which creates "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 larger the hole. IMO this is visually annoying. In addition, you have less free space until you reach a reasonable limit of 80/100-char.

I use this style when writing multi-line hashes / arrays / ... (pay attention to the comma also in the last element, so that we can easily arrange and simplify them):

 hash = { :a => 1, :b => 2, } array = [ :a, :b, ] 
+4
source

I would use option A.

Here is what ActiveRecord code is, too.

https://github.com/rails/rails/blob/master/activerecord/lib/active_record/associations/has_many_association.rb#L35

EDIT:

This is a rather stubborn question, most likely there is no right answer. Because of this, no matter how you do it, as long as it’s not just ugly code, people probably won’t hold it against you.

+3
source

I would not be caught dead using the value of an if block. Maybe because I came from the background, where if is a statement, not an expression ... So, my two cents:

 def load_business @business ||= ( params[:badge_uuid] ? # some code : # some other code) end 

If the code snippets are not explicit expressions, I would assign them a value in each if part and assign this variable to update @business .

+2
source

Source: https://habr.com/ru/post/1389498/


All Articles