THpubs
THpubs

Reputation: 8162

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

Upvotes: 6

Views: 4355

Answers (1)

seph
seph

Reputation: 6076

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

Upvotes: 13

Related Questions