如何摆脱几个方法的调用

时间:2019-03-08 01:10:05

标签: ruby-on-rails ruby-on-rails-5

我有一个Search类,其中有一个处理请求并返回用户ID的方法。

另外,我有三种基于结果数的方法,它们是计算特定类别中的用户数。

但是事实证明,我必须调用方法base_lead_scope 4次,是否可以摆脱它?

def initialize(opts = {})
  opts.symbolize_keys!
  @params = opts[:params]
  @current_team = opts[:current_team]
  @current_user = opts[:current_user]
  @scope = base_lead_scope(opts[:overrides] || {})
end

def archived_count
  @archived_count ||= base_lead_scope(overrides: { archived: true })
                                      .including_referrals(user: current_user, team: current_team)
                                      .archived.total_count
end

def recruiting_count
  @recruiting_count ||= base_lead_scope(overrides: { archived: false })
                                        .including_referrals(user: current_user, team: current_team)
                                        .recruiting_status.total_count
end

def retention_count
  @retention_count ||= base_lead_scope(overrides: { archived: false })
                                        .including_referrals(user: current_user, team: current_team)
                                        .retention_status.total_count
end

1 个答案:

答案 0 :(得分:1)

您可以将其写为

def get_count_of(status)
  @archived_count ||= base_lead_scope(overrides: { archived: (status == :archieved ? true : false) })
    .including_referrals(user: current_user, team: current_team)
    .public_send(status)
    .total_count
end

因此您可以按以下方式在状态参数中传递这些属性,

get_count_of(:archived)
get_count_of(:recruiting_status)
get_count_of(:retention_status)