From f15bd93861db8ad2b4df49f366c7b02db0845e6f Mon Sep 17 00:00:00 2001 From: Terrance Koar Date: Fri, 5 Apr 2024 09:34:26 -0400 Subject: [PATCH] adds methods to add and subtract priorities without type coercion --- Gemfile.lock | 2 +- lib/delayed/priority.rb | 12 ++++++++++-- spec/delayed/priority_spec.rb | 9 +++++++++ 3 files changed, 20 insertions(+), 3 deletions(-) diff --git a/Gemfile.lock b/Gemfile.lock index f3a89e7..e250e5f 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -1,7 +1,7 @@ PATH remote: . specs: - delayed (0.5.3) + delayed (0.5.4) activerecord (>= 5.2) concurrent-ruby diff --git a/lib/delayed/priority.rb b/lib/delayed/priority.rb index 233a1db..951f628 100644 --- a/lib/delayed/priority.rb +++ b/lib/delayed/priority.rb @@ -117,11 +117,11 @@ def default_alerts def names_to_midpoint_priority names.each_cons(2).to_h { |(name, priority_value), (_, next_priority_value)| [name, new(midpoint(priority_value, next_priority_value))] - }.merge(names.keys.last => new(names.values.last.to_i + 5)) + }.merge(names.keys.last => new(names.values.last + 5)) end def midpoint(low, high) - low.to_i + ((high.to_i - low.to_i).to_d / 2).ceil + low + ((high - low).to_d / 2).ceil end def respond_to_missing?(method_name, include_private = false) @@ -173,6 +173,14 @@ def <=>(other) to_i <=> other end + def -(other) + to_i - other.to_i + end + + def +(other) + to_i + other.to_i + end + private def respond_to_missing?(method_name, include_private = false) diff --git a/spec/delayed/priority_spec.rb b/spec/delayed/priority_spec.rb index f50f026..c758896 100644 --- a/spec/delayed/priority_spec.rb +++ b/spec/delayed/priority_spec.rb @@ -226,4 +226,13 @@ ].sort, ).to eq [-13, 3, 5, 40] end + + it 'supports addition and subtraction' do + expect(described_class.new(0) + 10).to eq(10) + expect(10 + described_class.new(5)).to eq(15) + expect(described_class.new(0) + described_class.new(33)).to eq(33) + expect(described_class.new(10) - 5).to eq(5) + expect(15 - described_class.new(10)).to eq(5) + expect(described_class.new(5) - described_class.new(15)).to eq(-10) + end end