Skip to content

Commit

Permalink
Implement iterator-returning Fugit::Cron#next
Browse files Browse the repository at this point in the history
and `#prev`
  • Loading branch information
jmettraux committed Feb 16, 2024
1 parent d2b4a58 commit 0734a57
Show file tree
Hide file tree
Showing 3 changed files with 78 additions and 0 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

## fugit 1.10.0 not yet released

* Implement iterator-returning `Fugit::Cron#next` and `#prev`


## fugit 1.9.0 released 2023-10-24

Expand Down
27 changes: 27 additions & 0 deletions lib/fugit/cron.rb
Original file line number Diff line number Diff line change
Expand Up @@ -318,6 +318,33 @@ def previous_time(from=::EtOrbi::EoTime.now)
t.time.translate(from.zone)
end

# Used by Fugit::Cron#next and Fugit::Cron#prev
#
class CronIterator include ::Enumerable
attr_reader :cron, :start, :current, :direction
def initialize(cron, direction, start)
@cron = cron
@start = start
@current = start.dup
@direction = direction
end
def each
loop do
yield(@current = @cron.send(@direction, @current))
end
end
end

def next(from=::EtOrbi::EoTime.now)

CronIterator.new(self, :next_time, from)
end

def prev(from=::EtOrbi::EoTime.now)

CronIterator.new(self, :previous_time, from)
end

# Mostly used as a #next_time sanity check.
# Avoid for "business" use, it's slow.
#
Expand Down
49 changes: 49 additions & 0 deletions spec/cron_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -1631,6 +1631,55 @@ class Fugit::Cron::TimeCursor
end
end
end

describe '#within' do
end

describe '#next' do

it 'returns an iterator' do

c = Fugit.parse_cron('0 12 * * mon#2')

in_zone 'UTC' do

expect(
c.next
.take(5)
.map(&:to_s)
).to eq([
'2024-03-11 12:00:00 Z',
'2024-04-08 12:00:00 Z',
'2024-05-13 12:00:00 Z',
'2024-06-10 12:00:00 Z',
'2024-07-08 12:00:00 Z'
])
end
end
end

describe '#prev' do

it 'returns an iterator' do

c = Fugit.parse_cron('0 12 * * mon#2')

in_zone 'UTC' do

expect(
c.prev
.take(5)
.map(&:to_s)
).to eq([
'2024-02-12 12:00:00 Z',
'2024-01-08 12:00:00 Z',
'2023-12-11 12:00:00 Z',
'2023-11-13 12:00:00 Z',
'2023-10-09 12:00:00 Z'
])
end
end
end
end

describe Fugit do
Expand Down

0 comments on commit 0734a57

Please sign in to comment.