Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 13 additions & 4 deletions lib/money/money/arithmetic.rb
Original file line number Diff line number Diff line change
Expand Up @@ -192,10 +192,14 @@ def *(value)
#
def /(value)
if value.is_a?(self.class)
fractional / as_d(value.exchange_to(currency).fractional).to_f
exchanged = value.exchange_to(currency)
raise ZeroDivisionError, "divided by Money(0)" if exchanged.zero?
Copy link
Member

@sunny sunny Jul 23, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you add specs for each of these raised errors? 🙏🏻

fractional / as_d(exchanged.fractional).to_f
else
raise TypeError, 'Can not divide by Money' if value.is_a?(CoercedNumeric)
dup_with(fractional: fractional / as_d(value))
value = value.value if value.is_a?(CoercedNumeric)
value = as_d(value)
raise ZeroDivisionError, "divided by zero" if value.zero?
dup_with(fractional: fractional / value)
end
end

Expand Down Expand Up @@ -232,13 +236,16 @@ def divmod(val)

def divmod_money(val)
cents = val.exchange_to(currency).cents
raise ZeroDivisionError, "divided by Money(0)" if cents == 0
quotient, remainder = fractional.divmod(cents)
[quotient, dup_with(fractional: remainder)]
end
private :divmod_money

def divmod_other(val)
quotient, remainder = fractional.divmod(as_d(val))
val = as_d(val)
raise ZeroDivisionError, "divided by zero" if val.zero?
quotient, remainder = fractional.divmod(val)
[dup_with(fractional: quotient), dup_with(fractional: remainder)]
end
private :divmod_other
Expand Down Expand Up @@ -326,6 +333,8 @@ def nonzero?
# @example
# 2 * Money.new(10) #=> #<Money @fractional=20>
def coerce(other)
raise TypeError, "Cannot divide Numeric by Money" if caller_locations(1,1).first.label == "/"
Copy link
Member

@sunny sunny Jul 23, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Relying on the caller locations may not be the most robust way to handle this and looks like it could imply a slight performance penalty. Would there be another way to do this?


[self, CoercedNumeric.new(other)]
end
end
Expand Down