ruby-on-rails - Rails 用守卫替换 if/elseif 块
问题描述
我使用 Prawn gem 在 PDF 中创建了一个现金交易表。为此,我遍历 Hash,parsed_cash_transactions
但在每个开始之前,我需要保存该last_item
Hash 以检查何时应在主表下方显示汇总表。
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
推荐阅读
- vue.js - 从 Vue 组件的 Javascript 部分到资产的路径
- python - 在 Python 中定义类变量时列表理解中未定义的变量
- c# - C# 反射方法 GetProperties(BindingFlags.Instance) 不返回子类对象
- ios - CollectionView 中的水平分页,就像 iPhone 相机中的一样(视频/慢动作/照片/等)
- blender - Cesium:gltf 文件的随机轮廓渲染
- python - 在python类的方法中获取self和class对象
- phpmyadmin - phpmyadmin mysql 数据库托管
- azure - Azure Blob 存储,如何实现任何文档或文件的版本
- php - 如何在找到单个记录时执行 mysql 查询,目标是返回 2 行
- javascript - setInterval 调用函数和html样式没有变化?