Sha256: 997850ac07fbda36f671847f9077e040d531c153e3a2f0064f8961b25b2850b5

Contents?: true

Size: 1.07 KB

Versions: 1

Compression:

Stored size: 1.07 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

      opts = Formatting.defaults.merge(opts)

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

      currency = opts.fetch(:currency) {
        record.respond_to?(:currency) ? record.currency: nil
      }

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

      amount = 0 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.3 lib/formatting/currency.rb