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

Instance Method Summary collapse

Constructor Details

#initialize(**attributes) ⇒ CommandResult

Returns a new instance of CommandResult.

Parameters:

  • attributes (Hash{Symbol=>Object})

    initial named attributes



19
20
21
22
23
24
25
# File 'lib/command_result.rb', line 19

def initialize(**attributes)
  @attributes = {}
  @attributes[:exit_status] = 0
  @attributes[:stdout] = ''
  @attributes[:warning] = ''
  attributes.each { |name, value| @attributes[name] = value }
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



48
49
50
51
52
53
54
55
56
57
58
# File 'lib/command_result.rb', line 48

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:

  • (Boolean)


27
28
29
# File 'lib/command_result.rb', line 27

def failure?
  !success?
end

#new_linesObject



36
37
38
39
40
# File 'lib/command_result.rb', line 36

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

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

Returns:

  • (Boolean)


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

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

#success?Boolean

Returns true if the exit status is zero.

Returns:

  • (Boolean)

    true if the exit status is zero



32
33
34
# File 'lib/command_result.rb', line 32

def success?
  exit_status.zero?
end