Class: Cognizant::Process::TriggerDelegate

Inherits:
Object
  • Object
show all
Defined in:
lib/cognizant/process/trigger_delegate.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, process, options = {}, &block) ⇒ TriggerDelegate

Returns a new instance of TriggerDelegate.



8
9
10
11
12
13
14
15
16
# File 'lib/cognizant/process/trigger_delegate.rb', line 8

def initialize(name, process, options = {}, &block)
  @name, @process = name, process
  @mutex = Mutex.new
  @scheduled_events = []

  @trigger = Cognizant::Process::Triggers[@name].new(options, &block)
  # TODO: This is hackish even though it keeps trigger implementations simple.
  @trigger.instance_variable_set(:@delegate, self)
end

Instance Attribute Details

#mutexObject

Returns the value of attribute mutex.



6
7
8
# File 'lib/cognizant/process/trigger_delegate.rb', line 6

def mutex
  @mutex
end

#nameObject

Returns the value of attribute name.



6
7
8
# File 'lib/cognizant/process/trigger_delegate.rb', line 6

def name
  @name
end

#processObject

Returns the value of attribute process.



6
7
8
# File 'lib/cognizant/process/trigger_delegate.rb', line 6

def process
  @process
end

#scheduled_eventsObject

Returns the value of attribute scheduled_events.



6
7
8
# File 'lib/cognizant/process/trigger_delegate.rb', line 6

def scheduled_events
  @scheduled_events
end

Instance Method Details

#cancel_all_eventsObject



49
50
51
52
53
54
# File 'lib/cognizant/process/trigger_delegate.rb', line 49

def cancel_all_events
  Log[self].debug "Canceling all scheduled events"
  @mutex.synchronize do
    @scheduled_events.each {|_, thread| thread.kill}
  end
end

#dispatch!(event) ⇒ Object



27
28
29
# File 'lib/cognizant/process/trigger_delegate.rb', line 27

def dispatch!(event)
  @process.dispatch!(event, @name)
end

#notify(transition) ⇒ Object



18
19
20
# File 'lib/cognizant/process/trigger_delegate.rb', line 18

def notify(transition)
  @trigger.notify(transition)
end

#reset!Object



22
23
24
25
# File 'lib/cognizant/process/trigger_delegate.rb', line 22

def reset!
  @trigger.reset!
  self.cancel_all_events
end

#schedule_event(event, delay) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/cognizant/process/trigger_delegate.rb', line 31

def schedule_event(event, delay)
  # TODO: Maybe wrap this in a ScheduledEvent class with methods like cancel.
  thread = Thread.new(self) do |trigger|
    begin
      sleep(delay)
      trigger.dispatch!(event)
      trigger.mutex.synchronize do
        trigger.scheduled_events.delete_if { |_, thread| thread == Thread.current }
      end
    rescue StandardError => e
      puts(e)
      puts(e.backtrace.join("\n"))
    end
  end

  @scheduled_events.push([event, thread])
end