首页 > 解决方案 > Rails 用守卫替换 if/elseif 块

问题描述

我使用 Prawn gem 在 PDF 中创建了一个现金交易表。为此,我遍历 Hash,parsed_cash_transactions但在每个开始之前,我需要保存该last_itemHash 以检查何时应在主表下方显示汇总表。

  def transactions_row
    last_item = parsed_cash_transactions.last[:position]

    parsed_cash_transactions.each do |cash_transaction|
      # some operations with cash_transaction item
      table_end_position = cursor

      if last_item == cash_transaction[:position] && table_end_position < 204
        new_page
        draw_gray_line if cash_transaction[:position].to_i.even?
      elsif table_end_position < 15
        new_page
        draw_gray_line if cash_transaction[:position].to_i.even?
      end
    end
  end

为了处理我在if block下面得到的所有要求。我想知道是否有更好,更清洁的方法来代替它if block?也许我可以以某种方式使用警卫?

      if last_item == cash_transaction[:position] && table_end_position < 204
        new_page
        draw_gray_line if cash_transaction[:position].to_i.even?
      elsif table_end_position < 15
        new_page
        draw_gray_line if cash_transaction[:position].to_i.even?
      end

标签: ruby-on-railsruby

解决方案


您确实可以使用保护子句,尽管它不是最漂亮的,因为它的条件很长。

  def transactions_row
    last_item = parsed_cash_transactions.last[:position]

    parsed_cash_transactions.each do |cash_transaction|
      # some operations with cash_transaction item
      table_end_position = cursor

      next unless last_item == cash_transaction[:position] && table_end_position < 204 ||
                  table_end_position < 15

      new_page
      draw_gray_line if cash_transaction[:position].to_i.even?
    end
  end

推荐阅读