Class: Amount::Display

Inherits:
Object
  • Object
show all
Defined in:
lib/amount/display.rb

Overview

Formats amounts for UI output without changing their type.

Instance Method Summary collapse

Constructor Details

#initialize(amount) ⇒ Display

Returns a new instance of Display.

Parameters:



9
10
11
12
# File 'lib/amount/display.rb', line 9

def initialize(amount)
  @amount = amount
  @entry = amount.registry_entry
end

Instance Method Details

#formattedString

Returns:

  • (String)


15
16
17
# File 'lib/amount/display.rb', line 15

def formatted
  format("%.#{@entry.decimals}f", @amount.decimal)
end

#in_unit(unit) ⇒ BigDecimal

Parameters:

  • unit (Symbol)

Returns:

  • (BigDecimal)


45
46
47
48
# File 'lib/amount/display.rb', line 45

def in_unit(unit)
  unit_spec = fetch_display_unit(unit)
  @amount.decimal * Amount.coerce_decimal(unit_spec[:scale])
end

#to_sString

Returns:

  • (String)


39
40
41
# File 'lib/amount/display.rb', line 39

def to_s
  "#{@entry.symbol}|#{@amount.decimal.to_s("F")}"
end

#ui(unit: nil, direction: :floor, decorated: true) ⇒ String

Examples:

Amount.usdc("1.50").ui                       # => "$1.50"
Amount.usdc("1.50").ui(decorated: false)     # => "1.50"
Amount.gold("1").ui(unit: :gram)             # => "31.10 g"
Amount.gold("1").ui(unit: :gram, decorated: false)  # => "31.10"

Parameters:

  • unit (Symbol, nil) (defaults to: nil)
  • direction (Symbol) (defaults to: :floor)
  • decorated (Boolean) (defaults to: true)

    when ‘false`, omit the display symbol and return just the rounded number. Useful when the caller renders the currency label separately (e.g. in a column header or a chip).

Returns:

  • (String)


30
31
32
33
34
35
36
# File 'lib/amount/display.rb', line 30

def ui(unit: nil, direction: :floor, decorated: true)
  if unit
    render_display_unit(unit, direction, decorated:)
  else
    render_default(direction, decorated:)
  end
end