Sha256: 32459f0796c020bd45603da86d12085a42f3bfeb04418d300be548670740ef16

Contents?: true

Size: 1.64 KB

Versions: 3

Compression:

Stored size: 1.64 KB

Contents

# -*- encoding: utf-8 -*-

require 'active_support/core_ext/string/inflections'

module EventedBluepill
  class TriggerTimer < Coolio::TimerWatcher
    def initialize(trigger, event, delay)
      @trigger = trigger
      @event = event
      super(delay, false)
    end

    def on_timer
      begin
        @trigger.logger.info("Retrying from flapping")
        @trigger.dispatch!(@event)
        @trigger.remove_timer(self)
      rescue StandardError => e
        @trigger.logger.err(e)
        @trigger.logger.err(e.backtrace.join("\n"))
      end
    end
  end

  class Trigger
    @implementations = {}
    def self.inherited(klass)
      @implementations[klass.name.split('::').last.underscore.to_sym] = klass
    end

    def self.[](name)
      @implementations[name]
    end

    attr_accessor :process, :logger, :scheduled_events

    def initialize(process, options = {})
      self.process = process
      self.logger = options[:logger]
      self.scheduled_events = []
    end

    def reset!
      self.cancel_all_events
    end

    def notify(transition)
      raise "Implement in subclass"
    end

    def dispatch!(event)
      self.process.dispatch!(event, self.class.name.split("::").last)
    end

    def remove_timer(timer)
      self.scheduled_events.delete(timer)
    end

    def schedule_event(event, delay)
      timer = EventedBluepill::TriggerTimer.new(self, event, delay)
      self.scheduled_events << timer
      
      EventedBluepill::Event.attach(timer)
    end

    def cancel_all_events
      self.logger.info "Canceling all scheduled events"
      self.scheduled_events.each {|e| e.detach }
      self.scheduled_events.clear
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
evented_bluepill-0.0.52 lib/evented_bluepill/trigger.rb
evented_bluepill-0.0.51 lib/evented_bluepill/trigger.rb
evented_bluepill-0.0.50 lib/evented_bluepill/trigger.rb