重构几个if else语句

时间:2015-11-03 13:11:22

标签: ruby-on-rails

我有一个方法,我正在寻求重构,我知道有可能重构它,但我很不确定它应该如何最有效地完成。

  # Collection of Users questions
  def all_questions
    current_week = Time.zone.now.strftime('%V').to_i

    # biweekly
    odd_or_even_week = current_week.odd? ? 'odd_weeks' : 'even_weeks'

    # monthly
    beginning_week_of_month =
      Time.zone.now.beginning_of_month.strftime('%V').to_i
    end_week_of_month       =
      Time.zone.now.end_of_month.strftime('%V').to_i

    # quarter
    beginning_week_of_quarter =
      Time.zone.now.beginning_of_quarter.strftime('%V').to_i
    end_week_of_quarter       =
      Time.zone.now.end_of_quarter.strftime('%V').to_i

    # User's current week questions
    group_questions.weekly + questions.weekly +
      questions.send(odd_or_even_week.to_sym) +
      group_questions.send(odd_or_even_week.to_sym) +
    if current_week == beginning_week_of_month    then questions.start_of_month   + group_questions.start_of_month        else [] end +
    if current_week == end_week_of_month          then questions.end_of_month     + group_questions.end_of_month          else [] end +
    if current_week == beginning_week_of_quarter  then questions.start_of_quarter + group_questions.start_of_quarter      else [] end +
    if current_week == end_week_of_quarter        then questions.end_of_quarter   + group_questions.end_of_quarter        else [] end
  end

这是我的方法。我实际上在做的是检查当前周是否与分配给不同变量的几个标准中的一个匹配。如果当前周匹配,那么我想在列表中添加一个数组。

我正在进行重构的一些小问题说if else语句是如果我没有假的空数组的回退,那么在连接中我将有两个++紧挨着每个 - 其他因为它将获得前一个数组,如果midle中的那个是空的,则为该数组添加+运算符。从而产生一个数组。

question和group_questions是关联,调用它们的方法是在问题模型上看起来像这样的枚举:

  enum frequency: { weekly: 0, odd_weeks: 1, even_weeks: 2,
                    start_of_month: 3, end_of_month: 4,
                    start_of_quarter: 5, end_of_quarter: 6 }

有人对他们如何重构这一点有所了解吗?

1 个答案:

答案 0 :(得分:0)

def enums_required
  # do all time calculations here
  frequency_values = [Conversation.frequency[:weekly]] # always want weekly status
  frequency_values << Conversation.frequency[odd_or_even_week] 
  frequency_values << Conversation.frequency[:start_of_month] if current_week == beginning_week_of_month
  frequency_values << Conversation.frequency[:end_of_month] if current_week == end_week_of_month
  frequency_values << Conversation.frequency[:start_of_quarter] if current_week == beginning_week_of_quarter
  frequency_values << Conversation.frequency[:end_of_quarter] if current_week == end_week_of_quarter
  frequency_values
end

不要这样做

odd_or_even_week = current_week.odd? ? 'odd_weeks' : 'even_weeks'

然后拨打.to_sym

只需写一个符号

odd_or_even_week = current_week.odd? ? :odd_weeks : :even_weeks

现在在你的方法中你应该可以做到

freq = enums_required
group_questions.where(frequency: freq) + questions.where(frequency: freq)

因为我在轨道中使用了枚举,所以可能需要一段时间。这基本上是一个让你顺利进行的中间重构,它绝不会达到最佳状态。