Good code practice for assigning variables using a condition

I had this code:

if @locale
    HighVoltage.content_path = "#{@template_to_use}/pages/#{@locale}/"
else
    HighVoltage.content_path = 'pages/'
end

Now I have this version:

HighVoltage.content_path = @locale ?
    "#{@template_to_use}/pages/#{@locale}/" :
    'pages/'

What will be the proposed way to write this piece of code, the first or second version, or may be different

+4
source share
3 answers

In my opinion, this is the best option:

HighVoltage.content_path = 
  if @locale
    "#{@template_to_use}/pages/#{@locale}/"
  else
    'pages/'
  end

You do not repeat yourself with HighVoltage.content_path =, as in the first example that you provided. BUT some people find my approach to look a little ugly compared to this. Therefore, you can use it if you believe in the same.

It is better not to use the instruction A ? B : Cif it takes several lines.

. https://github.com/bbatsov/ruby-style-guide#use-if-case-returns.

+12

HighVoltage.content_path =
  if @locale
    "#{@template_to_use}/pages/#{@locale}/"
  else
    'pages/'
  end

https://github.com/bbatsov/ruby-style-guide#use-if-case-returns

+2

Why not use one line for a triple?

HighVoltage.content_path = @locale ? "#{@template_to_use}/pages/#{@locale}/" : 'pages/'

I think it is readable, and this is just a matter of preference ... If you want fewer lines of code to go over to the triple option, if you like the readability of the first option, then use this.

+2
source

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


All Articles