Sha256: 9d124457a1782875fccc2e177f7bc576f96f1b0c29c0444c33e39c8436e86ff0

Contents?: true

Size: 1.34 KB

Versions: 7

Compression:

Stored size: 1.34 KB

Contents

# frozen_string_literal: true

module Light
  module Services
    module Callbacks
      def self.included(base)
        base.extend ClassMethods
        base.class_eval do
          class << self
            attr_accessor :callbacks
          end
        end
      end

      private

      def run_callbacks(type, options = {})
        callbacks_by(type).each do |callback|
          break if !success? && !options[:force_run]
          send(callback[:method_name])
        end
      end

      def callbacks_by(type)
        all_callbacks.select { |callback| callback[:type] == type }
      end

      def all_callbacks
        return @_all_callbacks if defined?(@_all_callbacks)
        @_all_callbacks = self.class.ancestors.select { |klass| klass.ancestors.include?(::Light::Services::Base) }
                              .map(&:callbacks).compact.reverse.flatten.uniq
      end

      module ClassMethods
        def before(method_name)
          set_callback(:before, method_name)
        end

        def after(method_name)
          set_callback(:after, method_name)
        end

        def finally(method_name)
          set_callback(:finally, method_name)
        end

        def set_callback(type, method_name)
          self.callbacks ||= []
          self.callbacks << { type: type, method_name: method_name }
        end
      end
    end
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
light-services-0.6.3 lib/light/services/callbacks.rb
light-services-0.6.2 lib/light/services/callbacks.rb
light-services-0.6.1 lib/light/services/callbacks.rb
light-services-0.6.0 lib/light/services/callbacks.rb
light-services-0.5.4 lib/light/services/callbacks.rb
light-services-0.5.3 lib/light/services/callbacks.rb
light-services-0.5.2 lib/light/services/callbacks.rb