Skip to content

Commit

Permalink
Merge pull request #278 from ghiculescu/allocate-none
Browse files Browse the repository at this point in the history
Better error if `Money#allocate` called with an empty array
  • Loading branch information
elfassy committed Apr 10, 2024
2 parents 5c32a36 + 5d52586 commit 984a578
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 0 deletions.
4 changes: 4 additions & 0 deletions lib/money/allocator.rb
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,10 @@ def initialize(money)
# #=> [#<Money value:2.64 currency:USD>, #<Money value:5.27 currency:USD>, #<Money value:2.64 currency:USD>]

def allocate(splits, strategy = :roundrobin)
if splits.empty?
raise ArgumentError, 'at least one split must be provided'
end

splits.map!(&:to_r)
allocations = splits.inject(0, :+)

Expand Down
4 changes: 4 additions & 0 deletions spec/allocator_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,10 @@
expect { new_allocator(0.05).allocate([0.5,0.6]) }.to raise_error(ArgumentError)
end

specify "#allocate requires at least one split" do
expect { new_allocator(0.05).allocate([]) }.to raise_error(ArgumentError)
end

specify "#allocate will use rationals if provided" do
splits = [128400,20439,14589,14589,25936].map{ |num| Rational(num, 203953) } # sums to > 1 if converted to float
expect(new_allocator(2.25).allocate(splits)).to eq([Money.new(1.42), Money.new(0.23), Money.new(0.16), Money.new(0.16), Money.new(0.28)])
Expand Down

0 comments on commit 984a578

Please sign in to comment.