Class: CommandResult

Inherits:
Object show all
Defined in:
lib/command_result.rb

Overview

Encapsulates the result of executing a system command, storing its output, exit status, and any number of additional, arbitrary attributes.

Examples:

result = CommandResult.new(stdout: output, exit_status: $?.exitstatus,
                           duration: 1.23)
result.stdout        # => output
result.exit_status   # => 0
result.duration      # => 1.23
result.new_field = 42
result.new_field     # => 42
result.success?      # => true

Constant Summary collapse

ALL =
[
  EXIT_STATUS_OK = 0,
  EXIT_STATUS_FAIL = 127,
  EXIT_STATUS_REQUIRED_EMPTY = 248
].freeze

Instance Method Summary collapse

Constructor Details

#initialize(**attributes) ⇒ CommandResult

Returns a new instance of CommandResult.

Parameters:

  • initial named attributes



32
33
34
35
36
37
38
# File 'lib/command_result.rb', line 32

def initialize(**attributes)
  @attributes = {
    exit_status: EXIT_STATUS_OK,
    stdout: '',
    warning: ''
  }.merge(attributes)
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *args) ⇒ Object

# trap assignment to new_lines def new_lines=(value)

ww caller.deref[0..4], value
@attributes[:new_lines] = value

end



69
70
71
72
73
74
75
76
77
78
79
# File 'lib/command_result.rb', line 69

def method_missing(name, *args)
  key = name.to_s.chomp('=').to_sym

  if name.to_s.end_with?('=') # setter
    @attributes[key] = args.first
  elsif attribute?(name) # getter
    @attributes[name]
  else
    super
  end
end

Instance Method Details

#failure?Boolean

Returns:



40
41
42
# File 'lib/command_result.rb', line 40

def failure?
  !success?
end

#new_linesObject



49
50
51
52
53
# File 'lib/command_result.rb', line 49

def new_lines
  value = @attributes[:new_lines] || []
  ww caller.deref[0..4], value
  value
end

#respond_to_missing?(name, include_private = false) ⇒ Boolean

Returns:



81
82
83
84
# File 'lib/command_result.rb', line 81

def respond_to_missing?(name, include_private = false)
  key = name.to_s.chomp('=').to_sym
  attribute?(key) || super
end

#stdoutObject



55
56
57
# File 'lib/command_result.rb', line 55

def stdout
  @attributes[:stdout]
end

#success?Boolean

Returns true if the exit status is zero.

Returns:

  • true if the exit status is zero



45
46
47
# File 'lib/command_result.rb', line 45

def success?
  exit_status.zero?
end

#transformedObject



59
60
61
# File 'lib/command_result.rb', line 59

def transformed
  @attributes[:transformed]
end