[英]Rails helper pass negative symbol as argument in self method
In my Rails 6, Ruby 2.7 app I'm using ActionView::Helpers::NumberHelper
and number_to_currency
method.在我的 Rails 6、Ruby 2.7 应用程序中,我使用的是
ActionView::Helpers::NumberHelper
和number_to_currency
方法。 Everything works fine but in one place I need to have negative amount instead of positive.一切正常,但在一个地方我需要负数而不是正数。 To do so I created two methods:
为此,我创建了两种方法:
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
Both works well:两者都运作良好:
Formatters::CashbookDocumentAmountFormatter.call(cash_transactions.first.gross_amount)
=> "100,00 €"
Formatters::CashbookDocumentAmountFormatter.negative_amount(cash_transactions.first.gross_amount)
=> "-100,00 €"
But I'm not so sure if this is a good approach, tbh the code seems to be smelly.但我不太确定这是否是一个好方法,代码似乎很臭。 Is it possible to change those two methods into one?
是否可以将这两种方法合二为一? How to pass '-' or '+' as an argument inside of one of these methods?
如何在这些方法之一中将“-”或“+”作为参数传递?
Call call
from within negative_amount
.从
negative_amount
中调用call
。
def self.negative_amount(amount)
call(-amount)
end
The next question being, why have this method at all?下一个问题是,为什么要使用这种方法? The caller can write
formatter.call(-amount)
just as easily and more obviously.调用者可以更轻松、更明显地编写
formatter.call(-amount)
。
Note that you probably shouldn't hard-code currency formatting and instead make use if internationalization .请注意,您可能不应该对货币格式进行硬编码,而是使用 if internationalization 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.