Sha256: 9b1a1892625db45828e885e6cbbdb3dc71c21af2752ec69d69c9fdf1546b0c0f

Contents?: true

Size: 1.43 KB

Versions: 12

Compression:

Stored size: 1.43 KB

Contents

module CommandServiceObject
  module Hooks
    def self.included(base)
      base.send :extend, ClassMethods
      base.send :include, InstanceMethods

      class << base
        alias_method :_new, :new

        define_method :new do |command|
          _new(command).tap do |instance|
            instance.send(:setup_micros, _micros)
          end
        end
      end
    end

    module InstanceMethods
      attr_accessor :_called_micros

      def _called_micros
        @_called_micros ||= []
      end

      def rollback_micros
        _called_micros.reverse_each(&:rollback)
      end

      def setup_micros(micros)
        micros.each do |micro|
          method_name = micro.name.split('::').last.underscore

          # unrollable micros
          define_singleton_method("#{method_name}!") do |cmd|
            micro.new(cmd).call
          end

          # rollable micros
          define_singleton_method(method_name) do |cmd|
            obj = micro.new(cmd)
            result = obj.call

            _called_micros << obj
            result
          end
        end
      end
    end

    module ClassMethods
      cattr_accessor :_micros

      def _micros
        @_micros ||= Set.new([])
      end

      def micros(*names)
        service = to_s.split('::').first

        names.each do |name|
          obj = "#{service}/Usecases/Micros/#{name}".camelize.constantize
          _micros.add(obj)
        end
      end
    end
  end
end

Version data entries

12 entries across 12 versions & 1 rubygems

Version Path
command_service_object-1.3.0 lib/command_service_object/hooks.rb
command_service_object-1.2.1 lib/command_service_object/hooks.rb
command_service_object-1.1.1 lib/command_service_object/hooks.rb
command_service_object-1.1.0 lib/command_service_object/hooks.rb
command_service_object-1.0.0 lib/command_service_object/hooks.rb
command_service_object-0.6.5 lib/command_service_object/hooks.rb
command_service_object-0.6.4 lib/command_service_object/hooks.rb
command_service_object-0.6.3 lib/command_service_object/hooks.rb
command_service_object-0.6.2 lib/command_service_object/hooks.rb
command_service_object-0.6.1 lib/command_service_object/hooks.rb
command_service_object-0.6.0 lib/command_service_object/hooks.rb
command_service_object-0.5.11 lib/command_service_object/hooks.rb