Class: CodeOutput::Parser

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

Instance Method Summary collapse

Constructor Details

#initialize(filename) ⇒ Parser

Returns a new instance of Parser.

Raises:

  • (IOError)


8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/code_output.rb', line 8

def initialize filename
  @filename = File.expand_path(filename)
  raise IOError, "`#{filename}' is not readable" unless File.readable? filename

  @old_stdout = $stdout

  $stdout = StringIO.new
  $stdout.instance_eval do
    class << self
      attr_accessor :outputs

      alias_method :old_write, :write

      def write string
        (@outputs ||= []) << { line: caller.first, string: string }

        old_write string
      end
    end
  end
end

Instance Method Details

#capture_outputObject Also known as: run



30
31
32
33
34
35
36
37
38
# File 'lib/code_output.rb', line 30

def capture_output
  load @filename

  $stdout.close_write
  @output_stream = $stdout
  @output_stream.rewind

  $stdout = @old_stdout
end

#dump(filename) ⇒ Object



41
42
43
44
45
# File 'lib/code_output.rb', line 41

def dump filename
  File.open(filename, 'w') do |file|
    file.write file_with_output
  end
end

#file_with_outputObject



51
52
53
54
# File 'lib/code_output.rb', line 51

def file_with_output
  inject_output unless @file_with_output
  @file_with_output.join
end

#raw_outputObject



47
48
49
# File 'lib/code_output.rb', line 47

def raw_output
  @output_stream.string
end