ruby-on-rails - Rails 助手在 self 方法中将负号作为参数传递
问题描述
在我使用的 Rails 6、Ruby 2.7 应用程序ActionView::Helpers::NumberHelper
和number_to_currency
方法中。一切正常,但在一个地方我需要负数而不是正数。为此,我创建了两种方法:
formatters/document_amount_formatter.rb
module Formatters
# Formats the amount in a suitable form to be used in PDF creator.
class DocumentAmountFormatter
extend ActionView::Helpers::NumberHelper
# The method to call.
#
# @return [String]
def self.call(amount)
number_to_currency(amount.to_f, delimiter: '.', separator: ',', format: '%n €')
end
def self.negative_amount(amount)
number_to_currency(-amount.to_f, delimiter: '.', separator: ',', format: '%n €')
end
end
end
两者都运作良好:
Formatters::CashbookDocumentAmountFormatter.call(cash_transactions.first.gross_amount)
=> "100,00 €"
Formatters::CashbookDocumentAmountFormatter.negative_amount(cash_transactions.first.gross_amount)
=> "-100,00 €"
但我不太确定这是否是一个好方法,代码似乎很臭。是否可以将这两种方法合二为一?如何在这些方法之一中将“-”或“+”作为参数传递?
解决方案
call
从内部调用negative_amount
。
def self.negative_amount(amount)
call(-amount)
end
下一个问题是,为什么要使用这种方法?formatter.call(-amount)
调用者可以更轻松、更明显地编写代码。
请注意,您可能不应该对货币格式进行硬编码,而是使用 if internationalization。
推荐阅读
- mysql - 处理 mysql 列中的空值的最佳方法
- c# - 错误 Fody:没有找到织布工。通过他们的 nuget 包添加所需的编织者
- javascript - 如何将 ID 添加到 react-table 组件?
- html - 如何为所有 HTML 页面使用我的 CSS 中的通用标题?
- c# - Unity C# Json 读/写
- django - 如何在 Django 单元测试中验证我的上下文是否包含表单对象?
- string - 是否有字符串操作来上标某些值?
- python - 使用 nginx 烧瓶“redirect(url_for)”和“@login_required”错误
- javascript - 如何在 Dropzone 选项上设置命名函数表达式?
- html - 如何让 Bootstrap 4 页面适合实际的移动显示?