Class: CMD

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

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(cmd, options = nil) ⇒ CMD

Returns a new instance of CMD.



10
11
12
13
14
15
16
17
18
# File 'lib/cmd.rb', line 10

def initialize(cmd, options=nil)
 initialize_defaults if(@@default_options.nil?)
 self[:output] = ''
 self[:error] = ''
 
 @@default_options.each { |key, value| self[key] = value}
 options.each { |key, value| self[key] = value} unless(options.nil?)
 self[:command]=cmd
end

Class Method Details

.default_options(hash) ⇒ Object



21
22
23
# File 'lib/cmd.rb', line 21

def self.default_options(hash)
  hash.each { |key, value| @@default_options[key] = value}
end

Instance Method Details

#executeObject



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/cmd.rb', line 25

def execute
  self[:output] = ''
  self[:error] = ''
  begin
 puts self[:command] if(self[:echo_command])
  
 output = {output: [], error:  [] }
 Open3.popen3(self[:command]) do |stdin, stdout, stderr, wait_thr|
{:output => stdout,:error => stderr}.each do |key, stream|
  Thread.new do
  until(raw_line = stream.gets).nil? do
    output[key] << raw_line
    puts raw_line if(self[:echo_output])
  end
  end
end
wait_thr.join
   self[:output] = output[:output].join
   self[:error] = output[:error].join
self[:exit_code] = wait_thr.value.to_i
 end
  rescue Excpetion => e
 self[:error] = "#{self[:error]}\nException: #{e.to_s}"
 self[:exit_code]=1 unless(self[:exit_code].nil? || (self[:exit_code] == 0))
  end
  
  if(self[:debug])
 puts "command: #{self[:command]}" if(self[:quiet])
 puts "output: #{self[:output]}"
 puts "error: #{self[:error]}"
 puts "exit_code: #{self[:exit_code]}"
  end
  
  if((self[:exit_code] != 0) && !self[:ignore_exit_code])
 exception_text = self[:error]
 exception_text = self[:output] if(self[:error].empty?)
 raise exception_text 
  end
end