Sha256: d84b04f8ceef3157e8c1fb7743ed5709f798a70aa99b4c9c4ccddbc8ab61fd7e

Contents?: true

Size: 1.24 KB

Versions: 1

Compression:

Stored size: 1.24 KB

Contents

# frozen_string_literal: true

require 'active_support/core_ext/string'
require 'active_model'
require 'dry-initializer'
require 'dry-monads'

require 'command/input_middleware'
require 'command/interrupt'

module Command
  extend ActiveSupport::Concern

  # rubocop:disable Metrics/BlockLength
  included do
    extend Dry::Initializer
    include Dry::Monads[:result]
    include ActiveModel::Validations

    def initialize(inputs = {})
      super(Command::InputMiddleware.call(inputs))
    end

    def execute
      raise NotImplementedError
    end

    def run
      result = if valid?
                 begin
                   execute
                 rescue Command::Interrupt => e
                   errors.merge! e.errors
                 end
               end

      errors.empty? ? Success(result) : Failure(errors)
    end

    def compose(command, *args)
      outcome = command.run(*args)

      raise Command::Interrupt, outcome.failure if outcome.failure?

      outcome.value!
    end

    def inputs
      self.class.dry_initializer.attributes(self)
    end
  end
  # rubocop:enable Metrics/BlockLength

  class_methods do
    def run(inputs = {})
      new(inputs).run
    end

    def run!(inputs = {})
      run(inputs).value!
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
g2_command-0.3.0 lib/command.rb