Class: SimpleShell::Command

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

Overview

A command and it’s output

stdout and stderr are

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(shell) ⇒ Command

Returns a new instance of Command.



128
129
130
131
132
133
134
135
136
# File 'lib/simple_shell.rb', line 128

def initialize(shell)
  @shell = shell
  @base  = shell.base
  @env   = shell.env || {}

  @out = ""
  @err = ""
  @S   = -1
end

Instance Attribute Details

#errObject (readonly)

Returns the value of attribute err.



126
127
128
# File 'lib/simple_shell.rb', line 126

def err
  @err
end

#outObject (readonly)

Returns the value of attribute out.



126
127
128
# File 'lib/simple_shell.rb', line 126

def out
  @out
end

#SObject (readonly)

Returns the value of attribute S.



126
127
128
# File 'lib/simple_shell.rb', line 126

def S
  @S
end

Instance Method Details

#execute(command, *args, &block) ⇒ Object



138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
# File 'lib/simple_shell.rb', line 138

def execute(command, *args, &block)
  $stderr.puts("#{@env} #{command}, #{args}, #{@base}") if SimpleShell.noisy

  Open3.popen3(@env, "#{command}", *(args.collect { |a| "#{a}" }) , :chdir => @base) do |stdin, stdout, stderr, thread|

    threads = []
    if @shell.stdout_handler
      threads << Thread.new(@shell.stdout_handler, stdout) do |handler, io|
        while(line = io.gets)
          handler.call(line)
        end
      end
    end

    if @shell.stderr_handler
      threads << Thread.new(@shell.stderr_handler, stderr) do |handler, io|
        while(line = io.gets)
          handler.call(line)
        end
      end
    end

    if block_given?
      yield stdin
    end

    stdin.close

    threads.collect(&:join)

    @out = @shell.stdout_handler ? nil : stdout.read.chomp
    @err = @shell.stderr_handler ? nil : stderr.read.chomp
    @S   = thread.value rescue 0
  end
end

#S?Boolean

cheap copy of $?

Returns:

  • (Boolean)


175
176
177
# File 'lib/simple_shell.rb', line 175

def S?
  @S
end

#to_sObject

we just want to know the output of the command



180
181
182
# File 'lib/simple_shell.rb', line 180

def to_s
  @out
end