首先,我不熟悉关于stackoverflow的问题。如果您对此问题不满意,请让我知道为什么以及如何更改它。
所以我正在为我们的实习服务开发状态网页。
这是我拥有的代码,要清楚一点,我想使方法“ 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 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])