Sha256: 053f6c1915bf976d7da9c4b74714c380fb1ca2ab5bafd73f9e01c47b17fc02e7

Contents?: true

Size: 1.48 KB

Versions: 8

Compression:

Stored size: 1.48 KB

Contents

if defined?(Delayed)

  module StateManager
    # Adds support for a :delay property on event definitions. Events with a
    # delay set will be automatically sent after the delay. If the state is
    # changed such that the event is no longer available before the delay is
    # reached, it will be canceled.
    module DelayedJob

      class DelayedEvent < Struct.new(:path, :event, :state_manager)
        def perform
          return unless state_manager.respond_to_event?(event[:name]) &&
            state_manager.in_state?(path)
          state_manager.send_event! event[:name]
        end
      end

      module State

        def delayed_events
          self.class.specification.events.reject{|name,event|!event[:delay]}
        end

        def entered
          delayed_events.each do |name, event|
            delay = event[:delay]
            delayed_event = DelayedEvent.new(path, event, state_manager)
            Delayed::Job.enqueue delayed_event, :run_at => delay.from_now
          end
        end

        def exited
          # TODO: we currently just have logic inside the job itself which
          # skips the event if it is no longer relevant. This is not perfect.
          # Ideally we should cancel events in this method (requiring an
          # efficient way to do this without looping over all events).
        end
      end
    end

    class State
      include DelayedJob::State

      def entered
        super
      end

      def exited
        super
      end
    end
  end

end

Version data entries

8 entries across 8 versions & 1 rubygems

Version Path
state_manager-0.2.10 lib/state_manager/plugins/delayed_job.rb
state_manager-0.2.9 lib/state_manager/plugins/delayed_job.rb
state_manager-0.2.8 lib/state_manager/plugins/delayed_job.rb
state_manager-0.2.7 lib/state_manager/plugins/delayed_job.rb
state_manager-0.2.6 lib/state_manager/plugins/delayed_job.rb
state_manager-0.2.5 lib/state_manager/plugins/delayed_job.rb
state_manager-0.2.4 lib/state_manager/plugins/delayed_job.rb
state_manager-0.2.3 lib/state_manager/plugins/delayed_job.rb