Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Ruby how to put multiple lines in one guard clause?

I have the following line of code :

if params[:"available_#{district.id}"] == 'true'
    @deliverycharge = @product.deliverycharges.create!(districtrate_id: district.id)
    delivery_custom_price(district)
end

Rubocop highlight it and asks me to use a guard clause for it. How can I do it?

EDIT : Rubocop highlighted the first line and gave this message Use a guard clause instead of wrapping the code inside a conditional expression

like image 235
THpubs Avatar asked Jun 23 '15 01:06

THpubs


1 Answers

Don't know what the surrounding code looks like so let's assume your code is the entire body of a method. Then a guard clause might look like this:

def some_method
  return if params[:"available_#{district.id}"] != 'true'   #guard clause

  @deliverycharge = @product.deliverycharges.create!(districtrate_id: district.id)
  delivery_custom_price(district)
end
like image 110
seph Avatar answered Oct 17 '22 21:10

seph