Class: ClockworkMocks::Scheduler

Inherits:
Object
  • Object
show all
Defined in:
lib/clockwork_mocks/scheduler.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeScheduler

Returns a new instance of Scheduler.



7
8
9
# File 'lib/clockwork_mocks/scheduler.rb', line 7

def initialize
  @tasks = []
end

Instance Attribute Details

#tasksObject (readonly)

Returns the value of attribute tasks.



5
6
7
# File 'lib/clockwork_mocks/scheduler.rb', line 5

def tasks
  @tasks
end

Class Method Details

.init_rspec(allow, receive, clock_file = nil, &block) ⇒ Object



11
12
13
# File 'lib/clockwork_mocks/scheduler.rb', line 11

def self.init_rspec(allow, receive, clock_file = nil, &block)
  Scheduler.new.tap { |s| s.init_rspec(allow, receive, clock_file, &block) }
end

Instance Method Details

#every(interval, name, hash = {}, &block) ⇒ Object



55
56
57
# File 'lib/clockwork_mocks/scheduler.rb', line 55

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

#handler(&block) ⇒ Object



50
51
52
53
# File 'lib/clockwork_mocks/scheduler.rb', line 50

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

#init_rspec(allow, receive, clock_file = nil) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/clockwork_mocks/scheduler.rb', line 15

def init_rspec(allow, receive, clock_file = nil)
  allow.call(Clockwork).to receive.call(:handler) do |&block|
    handler(&block)
  end

  allow.call(Clockwork).to receive.call(:every) do |interval, name, hash, &block|
    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
end

#reset!Object



46
47
48
# File 'lib/clockwork_mocks/scheduler.rb', line 46

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

#workObject



36
37
38
39
40
41
42
43
44
# File 'lib/clockwork_mocks/scheduler.rb', line 36

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

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

    t.perform(@handler)
  end
end