First of all i am new to asking questions on stackoverflow. If you downvote this question please let me know why and how i can change it.
So i am working on a status webpage for our intern services.
This is the code i have and to be clear i want to make the method "most_recent_checkresult_ids" more slim:
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
How could i do that? I dont want redundant code and i know there is a way to shorten it but i dont know how.
You can simplify this code by limiting the if
condition to the part that actually varies, rather than repeating a larger section of code.
Also (a minor point), you can use Symbol#to_proc
to shorted the map
syntax:
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