Class: Syscmd::Command

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

Overview

A command to execute. You usually just use Syscmd::exec! to create and execute the command. A command object can be executed only once.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(cmd, *args) ⇒ Command

execute a system command.

cmd: the command to execute
args: command line arguments


37
38
39
40
41
42
# File 'lib/syscmd.rb', line 37

def initialize(cmd, *args)
  @cmd = cmd
  @args = *args
  @process_status = nil
  @executed = false
end

Instance Attribute Details

#argsObject (readonly)

array of arguments.



18
19
20
# File 'lib/syscmd.rb', line 18

def args
  @args
end

#cmdObject (readonly)

the command to execute.



16
17
18
# File 'lib/syscmd.rb', line 16

def cmd
  @cmd
end

#cmdlineObject (readonly)

build the command line for this command. Once the command line is created, it will be cached.



20
21
22
# File 'lib/syscmd.rb', line 20

def cmdline
  @cmdline
end

#executedObject (readonly) Also known as: executed?

check if the command was executed.



13
14
15
# File 'lib/syscmd.rb', line 13

def executed
  @executed
end

#exitcodeObject (readonly)

the exitcode of the executed command. returns nil



30
31
32
# File 'lib/syscmd.rb', line 30

def exitcode
  @exitcode
end

#process_statusObject (readonly)

exit status of the executed command.



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

def process_status
  @process_status
end

#stderrObject (readonly)

standard error of the executed command.



25
26
27
# File 'lib/syscmd.rb', line 25

def stderr
  @stderr
end

#stdoutObject (readonly)

standard output of the executed command.



23
24
25
# File 'lib/syscmd.rb', line 23

def stdout
  @stdout
end

Instance Method Details

#exec!Object

execute the command. raises AlreadyExecutedError if the command is already executed.



46
47
48
49
50
51
52
# File 'lib/syscmd.rb', line 46

def exec!
  raise AlreadyExecutedError.new("already executed with status #{process_status}") if self.executed?
  @process_status, pread, perr = Syscmd::popen(self.cmdline)
  @stdout = pread.read
  @stderr = perr.read
  self
end

#stderr_linesObject

get the stdout as lines.



65
66
67
68
69
70
71
72
# File 'lib/syscmd.rb', line 65

def stderr_lines
  if @stderr_lines.nil?
    stderr = self.stderr
    return nil unless stderr
    @stderr_lines = stderr.split(/\n/)
  end
  @stderr_lines
end

#stdout_linesObject

get the stdout as lines.



55
56
57
58
59
60
61
62
# File 'lib/syscmd.rb', line 55

def stdout_lines
  if @stdout_lines.nil?
    stdout = self.stdout
    return nil unless stdout
    @stdout_lines = stdout.split(/\n/)
  end
  @stdout_lines
end