Sha256: f0ae0fcbf2492b1b9743c94d3156504524e07b593fd40c503c0f1e44beb9b9a1

Contents?: true

Size: 1.38 KB

Versions: 4

Compression:

Stored size: 1.38 KB

Contents

# frozen_string_literal: true

require 'dry/effects/initializer'
require 'dry/effects/effect'
require 'dry/effects/instructions/raise'

module Dry
  module Effects
    class Stack
      extend Initializer
      include Enumerable
      include Dry::Equalizer(:providers)

      param :providers, default: -> { [] }

      def call(effect)
        if effect.is_a?(Effect) && (provider = provider(effect))
          if effect.keywords.empty?
            provider.public_send(effect.name, *effect.payload)
          else
            provider.public_send(effect.name, *effect.payload, **effect.keywords)
          end
        else
          yield
        end
      rescue ::Exception => e
        Instructions::Raise.new(e)
      end

      def push(provider)
        providers.unshift(provider)
        yield
      ensure
        providers.shift
      end

      def provider(effect)
        find { |p| p.provide?(effect) }
      end

      def each(&block)
        providers.each(&block)
      end

      def size
        providers.size
      end

      def empty?
        providers.empty?
      end

      def dup
        Stack.new(map(&:dup))
      end

      def to_s
        if empty?
          '#<Dry::Effects::Stack>'
        else
          stack = map(&:represent).reverse.join('->')

          "#<Dry::Effects::Stack #{stack}>"
        end
      end
      alias_method :inspect, :to_s
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
dry-effects-0.1.5 lib/dry/effects/stack.rb
dry-effects-0.1.4 lib/dry/effects/stack.rb
dry-effects-0.1.3 lib/dry/effects/stack.rb
dry-effects-0.1.2 lib/dry/effects/stack.rb