Rails if 中的保护子句

Guard clause in Rails if

我在我的应用程序中使用 Rubocop,它为此建议 Use a guard clause instead of wrapping the code inside a conditional expression。请提出一个干净的方法来重写它。

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

假设代码在一个方法中,您可以像这样编写一个保护条件:

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

但是,如果 geolocation 应该始终为真或假,我可能会这样写,它在没有 if 或保护条件的情况下工作:

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