我如何让我的助手代码更苗条?

How do i make my code for my helper more slim?

首先,我不熟悉在 Whosebug 上提问。如果您对这个问题投反对票,请告诉我为什么以及如何更改它。

所以我正在为我们的实习生服务制作一个状态网页。

这是我的代码,需要说明的是,我想让方法 "most_recent_checkresult_ids" 更简洁:


  1 class OverallStatus
  2   def initialize(check_ids)
  3     @check_ids = check_ids
  4   end
  5
  6   def ok?
  7     !not_ok?
  8   end
  9
 10   def not_ok?
 11     Checkresult.where(id: most_recent_checkresult_ids).where(status: false).exists?
 12   end
 13
 14
 15
 16   private
 17
 18   def most_recent_checkresult_ids
 19     if @check_ids == nil
 20    Checkresult
 21     .select(:check_id, "MAX(id) as id")
 22     .group(:check_id)
 23     .map { |cr| cr.id }
 24     else
 25    Checkresult
 26     .select(:check_id, "MAX(id) as id")
 27     .where(check_id: @check_ids)
 28     .group(:check_id)
 29     .map { |cr| cr.id }
 30     end
 31   end
 32 end

我该怎么做?我不想要冗余代码,我知道有一种方法可以缩短它,但我不知道如何。

您可以通过将 if 条件限制为实际变化的部分来简化此代码,而不是重复更大的代码部分。

另外(一个小问题),你可以使用 Symbol#to_proc 来简化 map 语法:

def most_recent_checkresult_ids
  check_results = Checkresult.select(:check_id, "MAX(id) as id")
  check_results = check_results.where(check_id: @check_ids) if @check_ids

  check_results.group(:check_id).map(&:id)
end

您不需要有状态 class 和大量助手。

class OverallStatus
  def self.ok?(check_ids = nil)
    ids = Checkresult.select(:check_id, "MAX(id) as id")
    ids = ids.where(check_id: check_ids) unless check_ids.nil?

    not Checkresult.where(id: ids, status: false).exists?
  end
end

并将其用作

OverallStatus.ok?([1, 2, 3])