Skip to content

Instantly share code, notes, and snippets.

@iamvery
Created March 1, 2019 16:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iamvery/3c5021088214e8dc165214624a5dbf97 to your computer and use it in GitHub Desktop.
Save iamvery/3c5021088214e8dc165214624a5dbf97 to your computer and use it in GitHub Desktop.
diff --git a/lib/money/money/arithmetic.rb b/lib/money/money/arithmetic.rb
index 38bc94e..19d6b79 100644
--- a/lib/money/money/arithmetic.rb
+++ b/lib/money/money/arithmetic.rb
@@ -125,10 +125,10 @@ class Money
[:+, :-].each do |op|
define_method(op) do |other|
unless other.is_a?(Money)
- if other.zero?
+ if other && other.zero?
return other.is_a?(CoercedNumeric) ? Money.empty(currency).public_send(op, self) : self
end
- raise TypeError
+ raise TypeError, "Cannot perform arithemtic on non-zero value: #{other.inspect}"
end
other = other.exchange_to(currency)
self.class.new(fractional.public_send(op, other.fractional), currency, bank)
diff --git a/spec/money/arithmetic_spec.rb b/spec/money/arithmetic_spec.rb
index 8856c9b..d04f3c2 100644
--- a/spec/money/arithmetic_spec.rb
+++ b/spec/money/arithmetic_spec.rb
@@ -218,6 +218,10 @@ describe Money do
expect(special_money_class.new(10_00, "USD") + Money.new(90, "USD")).to be_a special_money_class
end
+ it "raises TypeError when added to nil" do
+ expect { Money.zero + nil }.to raise_exception(TypeError)
+ end
+
it_behaves_like 'instance with custom bank', :+, Money.new(1)
end
@@ -241,6 +245,10 @@ describe Money do
expect(special_money_class.new(10_00, "USD") - Money.new(90, "USD")).to be_a special_money_class
end
+ it "raises TypeError when added to nil" do
+ expect { Money.zero - nil }.to raise_exception(TypeError)
+ end
+
it_behaves_like 'instance with custom bank', :-, Money.new(1)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment