Sha256: ff711fbe5c1e80eb193952924aaf8d5335591a39952c8ccc483ec58c43721c09

Contents?: true

Size: 1.16 KB

Versions: 2

Compression:

Stored size: 1.16 KB

Contents

# frozen_string_literal: true

module ClockworkMocks
  class Scheduler
    attr_reader :tasks

    def initialize
      @tasks = []
    end

    def self.init_rspec(allow, receive, clock_file = nil)
      scheduler = Scheduler.new

      allow.call(Clockwork).to receive.call(:handler) do |&block|
        scheduler.handler(&block)
      end

      allow.call(Clockwork).to receive.call(:every) do |interval, name, hash, &block|
        scheduler.every interval, name, hash, &block
      end

      if block_given?
        yield
      else
        unless clock_file
          rails = Object.const_get('Rails')
          clock_file = "#{rails.root}/clock.rb" if rails
        end

        load clock_file if clock_file
      end

      scheduler
    end

    def work
      loop do
        t = @tasks.min_by(&:due)

        break if t.nil? || t.due > Time.now

        t.perform(@handler)
      end
    end

    def reset!
      @tasks.each(&:reset!)
    end

    def handler(&block)
      return @handler unless block_given?
      @handler = block
    end

    def every(interval, name, hash = {}, &block)
      @tasks.push ClockworkTask.new(interval, name, hash, block)
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
clockwork-mocks-1.1.1 lib/clockwork_mocks/scheduler.rb
clockwork-mocks-1.1.0 lib/clockwork_mocks/scheduler.rb