首页 > 解决方案 > Rails 助手在 self 方法中将负号作为参数传递

问题描述

在我使用的 Rails 6、Ruby 2.7 应用程序ActionView::Helpers::NumberHelpernumber_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 €"

但我不太确定这是否是一个好方法,代码似乎很臭。是否可以将这两种方法合二为一?如何在这些方法之一中将“-”或“+”作为参数传递?

标签: ruby-on-railsruby

解决方案


call从内部调用negative_amount

    def self.negative_amount(amount)
      call(-amount)
    end

下一个问题是,为什么要使用这种方法?formatter.call(-amount)调用者可以更轻松、更明显地编写代码。

请注意,您可能不应该对货币格式进行硬编码,而是使用 if internationalization


推荐阅读