Module: KickAhead

Defined in:
lib/kick_ahead.rb,
lib/kick_ahead/job.rb,
lib/kick_ahead/version.rb

Defined Under Namespace

Classes: Job

Constant Summary collapse

OutOfInterval =
Class.new(StandardError)
NoTickIntervalConfigured =
Class.new(RuntimeError)
NoCurrentTimeConfigured =
Class.new(RuntimeError)
RAISE_EXCEPTION_STRATEGY =
:raise_exception
IGNORE_STRATEGY =
:ignore
HOOK_STRATEGY =
:hook
STRATEGIES =
[RAISE_EXCEPTION_STRATEGY, IGNORE_STRATEGY, HOOK_STRATEGY].freeze
VERSION =
"0.1.2"

Class Attribute Summary collapse

Class Method Summary collapse

Class Attribute Details

.current_timeObject

Returns the value of attribute current_time.



21
22
23
# File 'lib/kick_ahead.rb', line 21

def current_time
  @current_time
end

.repositoryObject

Returns the value of attribute repository.



20
21
22
# File 'lib/kick_ahead.rb', line 20

def repository
  @repository
end

.tick_intervalObject

Returns the value of attribute tick_interval.



19
20
21
# File 'lib/kick_ahead.rb', line 19

def tick_interval
  @tick_interval
end

Class Method Details

.create_active_record_repository_for(ar_model) ⇒ Object



66
67
68
# File 'lib/kick_ahead.rb', line 66

def create_active_record_repository_for(ar_model)
  ArRepository.new(ar_model)
end

.out_of_time_job(job) ⇒ Object



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/kick_ahead.rb', line 46

def out_of_time_job(job)
  case constantize(job[:job_class]).out_of_time_strategy.to_sym
    when RAISE_EXCEPTION_STRATEGY
      raise OutOfInterval, "The job of class #{job[:job_class]} with args #{job[:job_args].inspect} "\
                      'was not possible to run because of an out of interval tick '\
                      "(we didn't receive a tick in time to run it) and it's maximum tolerance "\
                      'threshold is also overdue.'

    when IGNORE_STRATEGY
      KickAhead.repository.delete(job[:id])

    when HOOK_STRATEGY
      constantize(job[:job_class]).new.out_of_time_hook(job[:scheduled_at], *job[:job_args])
      KickAhead.repository.delete(job[:id])

    else
      raise 'Invalid strategy'
  end
end

.run_job(job) ⇒ Object



41
42
43
44
# File 'lib/kick_ahead.rb', line 41

def run_job(job)
  constantize(job[:job_class]).new.perform(*job[:job_args])
  KickAhead.repository.delete(job[:id])
end

.tickObject



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/kick_ahead.rb', line 23

def tick
  if tick_interval.nil?
    raise NoTickIntervalConfigured, 'No tick_interval configured! Please set `KickAhead.tick_interval`'
  end

  if current_time.nil?
    raise NoCurrentTimeConfigured, 'You must configure a current_time lambda (i.e.: KickAhead.current_time = -> { Time.current })'
  end

  KickAhead.repository.each_job_in_the_past do |job|
    if job[:scheduled_at] < KickAhead.current_time.call - tick_interval - constantize(job[:job_class]).tolerance
      out_of_time_job(job)
    else
      run_job(job)
    end
  end
end