Class: CaptureIO

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

Constant Summary collapse

VERSION =
'0.1.1'

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeCaptureIO

Returns a new instance of CaptureIO.



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

def initialize
   unless File.directory?('io_redirect')
     FileUtils.mkdir 'io_redirect'
   end

   base = "#{__FILE__}".gsub("#{File.dirname(__FILE__)}/", "")
   
   @stdout_file = "io_redirect/#{Time.to_md5}_#{base}_stdout"
   @stderr_file = "io_redirect/#{Time.to_md5}_#{base}_stderr"
   @stdout_fd = File.open(@stdout_file, 'w+')
   @stderr_fd = File.open(@stderr_file, 'w+')
end

Instance Attribute Details

#stderr_fileObject (readonly)

Returns the value of attribute stderr_file.



7
8
9
# File 'lib/capture_io.rb', line 7

def stderr_file
  @stderr_file
end

#stdout_fileObject (readonly)

Returns the value of attribute stdout_file.



7
8
9
# File 'lib/capture_io.rb', line 7

def stdout_file
  @stdout_file
end

Instance Method Details

#startObject



21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/capture_io.rb', line 21

def start
  begin
    @orig_stdout = $stdout
    @orig_stderr = $stderr
    
    @new_stdout = IO.new(@stdout_fd.fileno, 'w+')
    @new_stderr = IO.new(@stderr_fd.fileno, 'w+')
    
    $stdout = @new_stdout
    $stderr = @new_stderr
  rescue => e
    p e
  end
end

#stop(delete_tmp = true) ⇒ Object



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
64
# File 'lib/capture_io.rb', line 35

def stop(delete_tmp=true)
  stdout_content, stderr_content = ''
  begin
    @new_stdout.flush
  rescue => e
  end
  begin
    @new_stderr.flush
  rescue => e
  end
  begin 
    $stdout = @orig_stdout   
  rescue => e
  end
  begin 
    $stderr = @orig_stderr
  rescue => e
  end
    
  begin 
    stdout_content = File.readlines(@stdout_file)
    stderr_content = File.readlines(@stderr_file)     
   @new_stdout.close
   @new_stderr.close
   FileUtils.rm_rf 'io_redirect' if delete_tmp
  rescue => e
  end
  
  {:stdout => stdout_content, :stderr => stderr_content }       
end