Sha256: 0d86b64795013279f8401fe6a528d7bfae87aed0d87ff9fc20a1bd9364765fb2

Contents?: true

Size: 1.18 KB

Versions: 22

Compression:

Stored size: 1.18 KB

Contents

# frozen_string_literal: true

require_relative "exceptions"

module Statesman
  class Callback
    attr_reader :from
    attr_reader :to
    attr_reader :callback

    def initialize(options = { from: nil, to: nil, callback: nil })
      unless options[:callback].respond_to?(:call)
        raise InvalidCallbackError, "No callback passed"
      end

      @from     = options[:from]
      @to       = Array(options[:to])
      @callback = options[:callback]
    end

    def call(*args)
      callback.call(*args)
    end

    def applies_to?(options = { from: nil, to: nil })
      matches(options[:from], options[:to])
    end

    private

    def matches(from, to)
      matches_all_transitions ||
        matches_to_state(from, to) ||
        matches_from_state(from, to) ||
        matches_both_states(from, to)
    end

    def matches_all_transitions
      from.nil? && to.empty?
    end

    def matches_from_state(from, to)
      (from == self.from && (to.nil? || self.to.empty?))
    end

    def matches_to_state(from, to)
      ((from.nil? || self.from.nil?) && self.to.include?(to))
    end

    def matches_both_states(from, to)
      from == self.from && self.to.include?(to)
    end
  end
end

Version data entries

22 entries across 22 versions & 1 rubygems

Version Path
statesman-12.0.0 lib/statesman/callback.rb
statesman-11.0.0 lib/statesman/callback.rb
statesman-10.2.3 lib/statesman/callback.rb
statesman-10.2.2 lib/statesman/callback.rb
statesman-10.2.1 lib/statesman/callback.rb
statesman-10.2.0 lib/statesman/callback.rb
statesman-10.1.0 lib/statesman/callback.rb
statesman-10.0.0 lib/statesman/callback.rb
statesman-9.0.1 lib/statesman/callback.rb
statesman-9.0.0 lib/statesman/callback.rb
statesman-8.0.3 lib/statesman/callback.rb
statesman-8.0.2 lib/statesman/callback.rb
statesman-8.0.1 lib/statesman/callback.rb
statesman-8.0.0 lib/statesman/callback.rb
statesman-7.4.1 lib/statesman/callback.rb
statesman-7.4.0 lib/statesman/callback.rb
statesman-7.3.0 lib/statesman/callback.rb
statesman-7.2.0 lib/statesman/callback.rb
statesman-7.1.0 lib/statesman/callback.rb
statesman-7.0.1 lib/statesman/callback.rb