Sha256: 5c8dee1f0cfd5931f63abafcd1f7ae1e65f8a8a165d561e67fab380a688b1f1b

Contents?: true

Size: 1.17 KB

Versions: 1

Compression:

Stored size: 1.17 KB

Contents

module Formatting
  class NotARecordError < StandardError; end

  module Currency
    include Number

    def format_currency(record, amount_or_method, opts = {})
      if record.is_a?(Symbol)
        raise NotARecordError, "Expected an object that could tell us its currency; got #{record.inspect}"
      end

      format_string = opts.fetch(:format, "<amount> <currency>")
      skip_currency = opts.fetch(:skip_currency, false)

      unless skip_currency
        currency = opts.fetch(:currency) {
          record.respond_to?(:currency) ? record.currency: nil
        }
        currency = nil if currency == false
      end

      if amount_or_method.is_a?(Symbol)
        amount = record.public_send(amount_or_method)
      else
        amount = amount_or_method
      end

      return "" if amount.nil?

      amount = format_number(amount, opts)
      apply_format_string(format_string, amount, currency)
    end

    private

    def apply_format_string(format_string, amount, currency)
      out = format_string.dup
      out.gsub!("<amount>", amount)
      out.gsub!("<currency>", currency.to_s)
      out.strip!
      out.gsub!(" ", NON_BREAKING_SPACE)
      out
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
formatting-0.0.8 lib/formatting/currency.rb