Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Good code practice for variable assignment using a condition [closed]

Tags:

ruby

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 would be the suggested way to write this piece of code, first or second version or may be other

like image 294
jacr1614 Avatar asked Dec 05 '22 01:12

jacr1614


2 Answers

In my opinion here is the best option:

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

You don't repeat yourself with HighVoltage.content_path = as in the first example that you have provided. BUT some people do find my approach to look a little bit ugly compared to this one. So you could use it if you believe the same.

You better not to use A ? B : C statement if it will take multiple lines.

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

like image 197
Maxim Pontyushenko Avatar answered Dec 28 '22 23:12

Maxim Pontyushenko


According to the ruby style guide this is prefered

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

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

like image 38
NateSHolland Avatar answered Dec 28 '22 23:12

NateSHolland