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

首先,我不熟悉关于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

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

fangsufang 回答:如何使我的助手代码更苗条?

您可以通过将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
,

您不需要有状态的课堂和大量的助手。

domain.com/happyhours/categoryname

并将其用作

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
本文链接:https://www.f2er.com/3066517.html

大家都在问