123456789_123456789_123456789_123456789_123456789_

Class: IRB::SourceFinder::Source

Relationships & Source Files
Inherits: Object
Defined in: lib/irb/source_finder.rb

Class Method Summary

Instance Attribute Summary

Instance Method Summary

Constructor Details

.new(file, line, ast_source = nil) ⇒ Source

[ GitHub ]

  
# File 'lib/irb/source_finder.rb', line 11

def initialize(file, line, ast_source = nil)
  @file = file
  @line = line
  @ast_source = ast_source
end

Instance Attribute Details

#binary_file?Boolean (readonly)

[ GitHub ]

  
# File 'lib/irb/source_finder.rb', line 21

def binary_file?
  # If the line is zero, it means that the target's source is probably in a binary file.
  @line.zero?
end

#file (readonly)

[ GitHub ]

  
# File 'lib/irb/source_finder.rb', line 10

attr_reader :file, :line

#file_exist?Boolean (readonly)

[ GitHub ]

  
# File 'lib/irb/source_finder.rb', line 17

def file_exist?
  File.exist?(@file)
end

#line (readonly)

[ GitHub ]

  
# File 'lib/irb/source_finder.rb', line 10

attr_reader :file, :line

Instance Method Details

#colorized_content

[ GitHub ]

  
# File 'lib/irb/source_finder.rb', line 30

def colorized_content
  if !binary_file? && file_exist?
    # To correctly colorize, we need to colorize full content and extract the relevant lines.
    colored_lines = IRB::Color.colorize_code(file_content).lines

    # Handle wrong line number case: line_no passed to eval is wrong, file is edited after load, etc
    return if colored_lines.size < @line

    colored_lines[@line - 1...find_end].join
  elsif @ast_source
    IRB::Color.colorize_code(@ast_source)
  end
end

#file_content

[ GitHub ]

  
# File 'lib/irb/source_finder.rb', line 26

def file_content
  @file_content ||= File.read(@file)
end

#find_end (private)

[ GitHub ]

  
# File 'lib/irb/source_finder.rb', line 46

def find_end
  code = file_content
  lines = code.lines[(@line - 1)..-1]

  lines.each_with_index do |line, index|
    sub_code = lines.take(index + 1).join
    return @line + index if Prism.parse_success?(sub_code)
  end
  @line
end