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. Uses the fast path (to_r.round) when no custom mode is active.

Parameters:

  • amount (Numeric)
  • ndigits (Integer)

Returns:

  • (Rational)


32
33
34
35
36
37
38
39
# File 'lib/minting/mint/rounding.rb', line 32

def self.apply(amount, ndigits)
  mode = Thread.current[:minting_rounding_mode]
  if mode
    MODES.fetch(mode).call(amount.to_r, ndigits)
  else
    amount.to_r.round(ndigits)
  end
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



47
48
49
50
51
52
53
54
55
# File 'lib/minting/mint/rounding.rb', line 47

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