Sha256: fb57a4a45f1300bf3ab675cb663f5c575aae1b59f3c2e328014fb7fa3798f1d7

Contents?: true

Size: 1.4 KB

Versions: 2

Compression:

Stored size: 1.4 KB

Contents

# frozen_string_literal: true

require 'dry/effects/provider'

module Dry
  module Effects
    module Providers
      class Reader < Provider[:reader]
        def self.handle_method(scope, as: Undefined, **)
          Undefined.default(as) { :"with_#{scope}" }
        end

        Any = Object.new.tap { |any|
          def any.===(_)
            true
          end
        }.freeze

        include Dry::Equalizer(:scope, :state)

        attr_reader :state

        param :scope

        option :type, as: :state_type, default: -> { Any }

        def initialize(*)
          super

          @state = Undefined
        end

        def read
          state
        end

        # Yield the block with the handler installed
        #
        # @api private
        def call(stack, state)
          case state
          when state_type
            @state = state
            super(stack)
          else
            raise Errors::InvalidValueError.new(state, scope)
          end
        end

        # @return [String]
        # @api public
        def represent
          if Undefined.equal?(state)
            "#{type}[#{scope} not set]"
          else
            "#{type}[#{scope} set]"
          end
        end

        # @return [Boolean]
        # @api public
        def provide?(effect)
          effect.type.equal?(:state) && effect.name.equal?(:read) && scope.equal?(effect.scope)
        end
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
dry-effects-0.1.1 lib/dry/effects/providers/reader.rb
dry-effects-0.1.0 lib/dry/effects/providers/reader.rb