From adb9c9495a548f649400ccd67581e3ab15198b2a Mon Sep 17 00:00:00 2001 From: Mara Chimeno Date: Thu, 24 Oct 2024 14:55:59 +0000 Subject: [PATCH] adds new method --- lib/public/versions.rb | 13 +++++++++ lib/public/versions/version.rb | 5 ++++ spec/public/versions_spec.rb | 48 +++++++++++++++++++++++++++++----- 3 files changed, 60 insertions(+), 6 deletions(-) diff --git a/lib/public/versions.rb b/lib/public/versions.rb index da88386..97b9d82 100644 --- a/lib/public/versions.rb +++ b/lib/public/versions.rb @@ -25,6 +25,19 @@ def find!(name) find(name) || raise("Version '#{name}' not found") end + sig { params(name: String).returns(T.nilable(Version)) } + def find_next(name) + version = find!(name) + index = T.must(sorted_versions.index(version)) + + sorted_versions[index + 1] + end + + sig { returns(T::Array[Version]) } + def sorted_versions + versions.sort + end + private sig { returns(T::Array[Version]) } diff --git a/lib/public/versions/version.rb b/lib/public/versions/version.rb index fa572f1..68c44d2 100644 --- a/lib/public/versions/version.rb +++ b/lib/public/versions/version.rb @@ -26,6 +26,11 @@ def to_s def matches?(str) [name, *aliases].include?(str) end + + sig { params(other: Version).returns(T.nilable(Integer)) } + def <=>(other) + name <=> other.name + end end end end diff --git a/spec/public/versions_spec.rb b/spec/public/versions_spec.rb index 4bf19fb..a8297ab 100644 --- a/spec/public/versions_spec.rb +++ b/spec/public/versions_spec.rb @@ -6,12 +6,14 @@ RSpec.describe ResourceRegistry::Versions do subject do - described_class.new( - versions: [ - ResourceRegistry::Versions::Version.new('2024-01-01'), - ResourceRegistry::Versions::Version.new('2024-04-01', aliases: 'stable') - ] - ) + described_class.new(versions: versions) + end + + let(:versions) do + [ + ResourceRegistry::Versions::Version.new('2024-01-01'), + ResourceRegistry::Versions::Version.new('2024-04-01', aliases: 'stable') + ] end describe '#find!' do @@ -42,4 +44,38 @@ expect(subject.find!('stable').to_s).to eq('2024-04-01') end end + + describe '#find_next' do + context 'when given an old version' do + it 'returns the following version' do + expect(subject.find_next('2024-01-01').to_s).to eq('2024-04-01') + end + end + + context 'when given the last version' do + it 'does not returns a version' do + expect(subject.find_next('2024-04-01')).to be_nil + end + end + + context 'when given a random value' do + it 'does not returns a version' do + expect(subject.find_next('2024-04-01')).to be_nil + end + end + + context 'when given a list of unsorted versions' do + let(:versions) do + [ + ResourceRegistry::Versions::Version.new('2024-03-01', aliases: 'stable'), + ResourceRegistry::Versions::Version.new('2024-04-01', aliases: 'deprecated'), + ResourceRegistry::Versions::Version.new('2024-02-01') + ] + end + + it 'orders and returns the following version' do + expect(subject.find_next('2024-02-01').to_s).to eq('2024-03-01') + end + end + end end