Skip to content

Add ability to nest Money.with_rounding_mode blocks #1128

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 8 commits into
base: main
Choose a base branch
from

Conversation

pawelma
Copy link

@pawelma pawelma commented May 9, 2025

WHAT

Allow .with_rounding_mode blocks nesting

WHY

So, that we can safely use the block and not rely on global rounding_mode.

Relates to the comment in PR which introduced the feature #343 (comment)

pawelma and others added 7 commits May 9, 2025 14:30
so that it can emphasize it's behaviour better
So that it won't return to the global value in case if someone will
modify down in the stack.

For example we might have:
```ruby
	- initializers/money.rb
	Money.rounding_mode = BigDecimal::ROUND_HALF_EVEN

	- controllers/test.rb
	Money.with_rounding_mode(BigDecimal::ROUND_UP) do
	  object.amount = Money.from_amount(1.234)
	  object.save
	  other_object.amount = object.amount * different_rate
	end

	- models/object.rb
	def save
	  Money.with_rounding_mode(BigDecimal::ROUND_DOWN) do
	    self.tax = object.amount * tax_rate
	  end
	  ...
	end
```

Above example prior the change would cause other_object to use
`ROUND_HALF_EVEN`, despite it's explicitly defined in a `with_rounding_mode`
block which sets `ROUND_UP`.

The small rounding errors might be tricky to debug,
and in worst case scenarios can cumulate to a bigger differences when
code operates on multiple amounts that might be incorrectly rounded.

Co-Authored-By: Łukasz Wójcik <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants