Class: Duple::Runner

Inherits:
Object
  • Object
show all
Defined in:
lib/duple/runner.rb

Overview

Helper class for executing shell commands.

Instance Method Summary collapse

Constructor Details

#initialize(options = nil) ⇒ Runner

Returns a new instance of Runner.



8
9
10
11
12
13
14
15
16
17
18
19
20
# File 'lib/duple/runner.rb', line 8

def initialize(options = nil)
  options ||= {}
  @options = {
    log: STDOUT,
    log_format: ' * Running: %s',
    dry_run: false,
    recorder: nil
  }.merge(options)

  if recorder? && !valid_recorder?
    raise ArgumentError.new("Invalid :recorder option: #{@options[:recorder]}")
  end
end

Instance Method Details

#capture(command) ⇒ Object



33
34
35
# File 'lib/duple/runner.rb', line 33

def capture(command)
  run(command, true)
end

#dry_run?Boolean

Returns:

  • (Boolean)


56
57
58
# File 'lib/duple/runner.rb', line 56

def dry_run?
  @options[:dry_run]
end

#log_command(command) ⇒ Object



41
42
43
44
45
46
# File 'lib/duple/runner.rb', line 41

def log_command(command)
  return unless @options[:log]

  formatted = @options[:log_format] % command
  @options[:log].puts formatted
end

#record_command(command) ⇒ Object



37
38
39
# File 'lib/duple/runner.rb', line 37

def record_command(command)
  @options[:recorder].puts command
end

#recorder?Boolean

Returns:

  • (Boolean)


52
53
54
# File 'lib/duple/runner.rb', line 52

def recorder?
  @options[:recorder]
end

#run(command, capture = false) ⇒ Object

Raises:

  • (RuntimeError)


22
23
24
25
26
27
28
29
30
31
# File 'lib/duple/runner.rb', line 22

def run(command, capture = false)
  log_command(command)
  record_command(command) if recorder?

  return if dry_run?

  result = capture ? `#{command}` : system(command)
  raise RuntimeError.new("Command failed: #{$?}") unless $?.success?
  result
end

#valid_recorder?Boolean

Returns:

  • (Boolean)


48
49
50
# File 'lib/duple/runner.rb', line 48

def valid_recorder?
  @options[:recorder].respond_to?(:puts)
end