From d66c643fa47354f76f86b3727cb889fc5a9ebe7c Mon Sep 17 00:00:00 2001 From: Bertie Croll Date: Sat, 17 Feb 2024 09:40:17 +0000 Subject: [PATCH 1/3] Fixes #money_only_cents for negative money When given negative money, #money_only_cents does not return the expected subunit value due to how modulo handles negative numbers, for example: -125 % 100 = 75 To fix, updates calculation to use absolute value. --- lib/money-rails/helpers/action_view_extension.rb | 2 +- spec/helpers/action_view_extension_spec.rb | 5 +++++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/lib/money-rails/helpers/action_view_extension.rb b/lib/money-rails/helpers/action_view_extension.rb index 4a5b88aa82..f6205946a7 100644 --- a/lib/money-rails/helpers/action_view_extension.rb +++ b/lib/money-rails/helpers/action_view_extension.rb @@ -53,7 +53,7 @@ def money_only_cents(value) value = value.to_money - format "%0#{value.currency.exponent}d", (value % value.currency.subunit_to_unit).cents + format "%0#{value.currency.exponent}d", (value.abs % value.currency.subunit_to_unit).cents end end end diff --git a/spec/helpers/action_view_extension_spec.rb b/spec/helpers/action_view_extension_spec.rb index c62f53a081..c2bc5a22fa 100644 --- a/spec/helpers/action_view_extension_spec.rb +++ b/spec/helpers/action_view_extension_spec.rb @@ -105,6 +105,11 @@ let(:monetizable_object){ false } it { is_expected.to eq "00" } end + + context 'with a negative monetizable object' do + let(:monetizable_object){ Money.new(-125) } + it { is_expected.to eq "25" } + end end context 'respects MoneyRails::Configuration settings' do From ae0f3b3ca18bf51dda79cfded5cfa7b531104010 Mon Sep 17 00:00:00 2001 From: Bertie Croll Date: Sat, 17 Feb 2024 09:40:33 +0000 Subject: [PATCH 2/3] Adds money_only_cents fix to changelog --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2a452444eb..24760e14dd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,7 @@ ## Unreleased - Allow monetizing methods with kwargs +- Fix money_only_cents for negative money ## 1.15.0 From f9e6081c059f7c24215ce01c8fc084f2f199c355 Mon Sep 17 00:00:00 2001 From: Bertie Croll Date: Sat, 17 Feb 2024 12:55:59 +0000 Subject: [PATCH 3/3] Updates spec to clarify cents Co-authored-by: Sunny Ripert --- spec/helpers/action_view_extension_spec.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/spec/helpers/action_view_extension_spec.rb b/spec/helpers/action_view_extension_spec.rb index c2bc5a22fa..26a9ad5179 100644 --- a/spec/helpers/action_view_extension_spec.rb +++ b/spec/helpers/action_view_extension_spec.rb @@ -107,7 +107,7 @@ end context 'with a negative monetizable object' do - let(:monetizable_object){ Money.new(-125) } + let(:monetizable_object){ Money.new(-1_25) } it { is_expected.to eq "25" } end end