bhvd
bhvd

Reputation: 55

Guard clause in Rails if

I am using Rubocop in my application and it suggests Use a guard clause instead of wrapping the code inside a conditional expression for this. Plz suggest a clean way to rewrite it.

 if (geolocation_points.exists? || geolocation_boxes.exists?)
  self.geolocation = true
 end

Upvotes: 0

Views: 2500

Answers (1)

infused
infused

Reputation: 24337

Assuming that code is in a method you would write a guard condition like so:

def my_fancy_method
  return unless geolocation_points.exists? && geolocation_boxes.exists?
  self.geolocation = true
end

However, if geolocation should always either be true or false, I would probably write it as follows, which works without an if or a guard condition:

def my_fancy_method
  self.geolocation = geolocation_points.exists? && geolocation_boxes.exists?
end

Upvotes: 2

Related Questions