summaryrefslogtreecommitdiffhomepage
path: root/lib/dispatch/tools/result.rb
blob: 7e485130f4f7faf648bd400fbf77a4582801b48d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# frozen_string_literal: true

module Dispatch
  module Tools
    class Result
      attr_reader :output, :error, :metadata

      def self.success(output:, metadata: {})
        new(success: true, output:, error: nil, metadata:)
      end

      def self.failure(error:, metadata: {})
        new(success: false, output: nil, error:, metadata:)
      end

      def success?
        @success
      end

      def failure?
        !@success
      end

      def to_s
        success? ? output : error
      end

      def to_h
        {
          success: @success,
          output:,
          error:,
          metadata:
        }
      end

      private

      def initialize(success:, output:, error:, metadata:)
        @success = success
        @output = output
        @error = error
        @metadata = metadata
        freeze
      end
    end
  end
end