Module: Mint::Rounding Private

Defined in:
lib/minting/mint/rounding.rb

Overview

This module is part of a private API. You should avoid using this module if possible, as it may be removed or be changed in the future.

Rounding-mode dispatch table and block-scoped context.

Constant Summary collapse

MODES =

This constant is part of a private API. You should avoid using this constant if possible, as it may be removed or be changed in the future.

Maps mode symbols to their corresponding Rational rounding lambdas.

Returns:

  • (Hash{Symbol => Proc})
{
  half_up: ->(amount, ndigits) { amount.round(ndigits, half: :up) },
  half_down: ->(amount, ndigits) { amount.round(ndigits, half: :down) },
  floor: ->(amount, ndigits) { amount.floor(ndigits) },
  ceil: ->(amount, ndigits) { amount.ceil(ndigits) },
  truncate: ->(amount, ndigits) { amount.truncate(ndigits) },
  down: ->(amount, ndigits) { amount.truncate(ndigits) }
}.freeze

Class Method Summary collapse

Class Method Details

.apply(amount, ndigits) ⇒ Rational

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Rounds amount to ndigits using the currently scoped rounding mode.

Parameters:

  • amount (Numeric)
  • ndigits (Integer)

Returns:

  • (Rational)


31
32
33
# File 'lib/minting/mint/rounding.rb', line 31

def self.apply(amount, ndigits)
  MODES.fetch(current_mode).call(amount.to_r, ndigits)
end

.current_modeSymbol

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Returns the currently active rounding mode, falling back to :half_up.

Returns:

  • (Symbol)


22
23
24
# File 'lib/minting/mint/rounding.rb', line 22

def self.current_mode
  Thread.current[:minting_rounding_mode] || :half_up
end

.with_mode(mode) { ... } ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Sets a rounding mode for the duration of a block, restoring the previous mode on exit (even on exception).

Parameters:

  • mode (Symbol)

Yields:

  • block to execute with the mode active

Raises:

  • (ArgumentError)

    on unknown mode



41
42
43
44
45
46
47
48
49
# File 'lib/minting/mint/rounding.rb', line 41

def self.with_mode(mode)
  raise ArgumentError, "Unknown rounding mode: #{mode}" unless MODES.key?(mode)

  prev = Thread.current[:minting_rounding_mode]
  Thread.current[:minting_rounding_mode] = mode
  yield
ensure
  Thread.current[:minting_rounding_mode] = prev
end