Sha256: 3fb85ebb650e7f4a812a28755f83375274e20fc0bc2f7045823bdf4667220223

Contents?: true

Size: 1.78 KB

Versions: 3

Compression:

Stored size: 1.78 KB

Contents

# frozen_string_literal: true

module ConvenientService
  module Common
    module Plugins
      module HasCallbacks
        class Middleware < MethodChainMiddleware
          ##
          # @internal
          #   TODO: Support of callbacks for class methods.
          #
          intended_for any_method, entity: any_entity

          ##
          # @param args [Array<Object>]
          # @param kwargs [Hash{Symbol => Object}]
          # @param block [Proc, nil]
          # @return [Object] Can be any type.
          #
          # @internal
          #   TODO: Move to command.
          #
          def next(*args, **kwargs, &block)
            ##
            # class Service
            #   before :result do
            #   end
            #
            #   before :result do |arguments|
            #   end
            # end
            #
            callbacks.for([:before, method]).each { |callback| callback.call_in_context_with_arguments(entity, *args, **kwargs, &block) }

            original_value = chain.next(*args, **kwargs, &block)

            ##
            # class Service
            #   after :result do
            #   end
            #
            #   after :result do |result|
            #   end
            #
            #   after :result do |result, arguments|
            #   end
            # end
            #
            callbacks.for([:after, method]).reverse_each { |callback| callback.call_in_context_with_value_and_arguments(entity, original_value, *args, **kwargs, &block) }

            original_value
          end

          private

          ##
          # @return [ConvenientService::Common::Plugins::HasCallbacks::Entities::CallbackCollection]
          #
          def callbacks
            entity.class.callbacks
          end
        end
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
convenient_service-0.19.1 lib/convenient_service/common/plugins/has_callbacks/middleware.rb
convenient_service-0.19.0 lib/convenient_service/common/plugins/has_callbacks/middleware.rb
convenient_service-0.18.0 lib/convenient_service/common/plugins/has_callbacks/middleware.rb