class CutePrint::RubyParser

This class is very much cribbed from this excellent code:

https://github.com/sconover/wrong/blob/30475fc5ac9d0f73135d229b1b44c045156a7e7a/lib/wrong/chunk.rb

@api private

Public Class Methods

from_block(block) click to toggle source
# File lib/cute_print/ruby_parser.rb, line 15
def self.from_block(block)
  path, line_number = block.to_proc.source_location
  new(path, line_number, &block)
end
new(path, line_number, &block) click to toggle source
# File lib/cute_print/ruby_parser.rb, line 20
def initialize(path, line_number, &block)
  @path = path
  @line_number = line_number
  @block = block
end

Public Instance Methods

parse() click to toggle source
# File lib/cute_print/ruby_parser.rb, line 26
def parse
  @parsed ||= parse_source(read_source)
end

Private Instance Methods

parse_source(source) click to toggle source

Try parsing just the starting line. While that doesn't work, add another line and try again.

# File lib/cute_print/ruby_parser.rb, line 46
def parse_source(source)
  lines = source.lines.to_a
  starting_line_index = @line_number - 1
  ending_line_index = starting_line_index
  sexp = nil
  while !sexp && ending_line_index < lines.size
    begin
      snippet = lines.to_a[starting_line_index..ending_line_index].join
      sexp = parser.parse(snippet)
      return ParsedCode.new(sexp)
    rescue Racc::ParseError
      ending_line_index += 1
      raise if ending_line_index >= lines.size
    end
  end
end
parser() click to toggle source
# File lib/cute_print/ruby_parser.rb, line 40
def parser
  @parser ||= ::RubyParser.new
end
read_source() click to toggle source
# File lib/cute_print/ruby_parser.rb, line 32
def read_source
  if @path == '(irb)'
    IRB.CurrentContext.all_lines
  else
    File.read(@path)
  end
end