我使用Prawn gem在PDF中创建了一个现金交易表。为此,我使用parsed_cash_transactions
迭代哈希,但在每次开始之前,我需要保存该哈希的last_item
,以检查何时应该在主表下方显示汇总表。
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
您确实可以使用一个保护子句,尽管它不是最漂亮的,因为它的条件相当长。
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