ruby-on-rails - 许多非常相似的功能,意大利面条代码修复?

标签 ruby-on-rails ruby loops ruby-on-rails-4 iteration

我有大约 11 个如下所示的函数:

def pending_acceptance(order_fulfillments)
  order_fulfillments.each do |order_fulfillment|
    next unless order_fulfillment.fulfillment_time_calculator.
        pending_acceptance?; collect_fulfillments(
          order_fulfillment.status,
          order_fulfillment
        )
  end
end

def pending_start(order_fulfillments)
  order_fulfillments.each do |order_fulfillment|
    next unless order_fulfillment.fulfillment_time_calculator.
        pending_start?; collect_fulfillments(
          order_fulfillment.status,
          order_fulfillment
        )
  end
end

迭代总是相同的,但是 next unless 条件不同。如果您想知道:它是 next unless; 因为 RuboCop 提示它。有更好的解决方案吗?我讨厌这个意大利面条代码。诸如将条件传递给“iterate_it”函数之类的东西......

编辑:不能只传递另一个参数,因为条件有时是双重的:

def picked_up(order_fulfillments)
      order_fulfillments.each do |order_fulfillment|
        next unless
          order_fulfillment.handed_over_late? && order_fulfillment.
              fulfillment_time_calculator.pending_handover?
                collect_fulfillments(
                  order_fulfillment.status,
                  order_fulfillment
                )
      end
    end

edit2:还有一个问题:我如何切分符号,以从状态中获取用户角色?就像是: :deliverer_started => :deliverer 或 'deliverer'?

最佳答案

当你使用另一个参数来决定检查什么条件时,你可以传递另一个参数。只需将所有可能的条件存储为散列中的 lambda:

FULFILLMENT_ACTIONS = {
  pending_acceptance: lambda { |fulfillment| fulfillment.fulfillment_time_calculator.pending_acceptance? }, 
  pending_start:      lambda { |fulfillment| fulfillment.fulfillment_time_calculator.pending_acceptance? },
  picked_up:          lambda { |fulfillment| fulfillment.handed_over_late? && fulfillment.fulfillment_time_calculator.pending_handover? }
}

def process_fulfillments(type, order_fulfillments)
  condition = FULFILLMENT_ACTIONS.fetch(type)

  order_fulfillments.each do |order_fulfillment|
    next unless condition.call(order_fulfillment)
    collect_fulfillments(order_fulfillment.status, order_fulfillment)
  end
end

被称为:

process_fulfillments(:pending_acceptance, order_fulfillments)
process_fulfillments(:pending_start, order_fulfillments)
process_fulfillments(:picked_up, order_fulfillments)

关于ruby-on-rails - 许多非常相似的功能,意大利面条代码修复?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39242107/

相关文章:

ruby-on-rails - 仅针对特定代码路径调用 after_action

php - 使用 Passenger 与 PHP 应用程序一起运行 Rails 应用程序

javascript - JS/Ruby AES 256 对称性

c++ - FilePointer 陷入无限循环

ruby-on-rails - 增量计数器和 rails "first"使用 postgreSQL 奇怪的行为

ruby-on-rails - 为 lighttpd/thin 启用浏览器缓存

Java 到 ruby​​ AES/ECB/PKCS5Padding 加密

ruby-on-rails - 从哈希数组返回特定​​值 - JSON

python - Tkinter - 设置字符串变量并在循环时获取条目值

Java:简单的数组分割程序