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.



14
15
16
17
18
19
20
21
22
# File 'lib/cmd.rb', line 14

def initialize(cmd, options=nil)
 self.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



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

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

.initialize_defaultsObject



9
10
11
# File 'lib/cmd.rb', line 9

def self.initialize_defaults
  @@default_options = { echo_command: true, echo_output: true, ignore_exit_code: false, debug: false }
end

Instance Method Details

#executeObject



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
# File 'lib/cmd.rb', line 30

def execute
  #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

  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