mirror of
https://github.com/ruby/ruby.git
synced 2025-08-24 21:44:30 +02:00

(https://github.com/ruby/irb/pull/862)
* Powerup show_source by enabling RubyVM.keep_script_lines
* Add file_content field to avoid reading file twice while show_source
* Change path passed to eval, don't change irb_path.
* Encapsulate source coloring logic and binary file check insode class Source
* Add edit command testcase when irb_path does not exist
* Memoize irb_path existence to reduce file existence check calculating eval_path
239683a937
68 lines
1.7 KiB
Ruby
68 lines
1.7 KiB
Ruby
# frozen_string_literal: true
|
|
|
|
require_relative "nop"
|
|
require_relative "../source_finder"
|
|
require_relative "../pager"
|
|
require_relative "../color"
|
|
|
|
module IRB
|
|
module ExtendCommand
|
|
class ShowSource < Nop
|
|
category "Context"
|
|
description "Show the source code of a given method or constant."
|
|
|
|
class << self
|
|
def transform_args(args)
|
|
# Return a string literal as is for backward compatibility
|
|
if args.empty? || string_literal?(args)
|
|
args
|
|
else # Otherwise, consider the input as a String for convenience
|
|
args.strip.dump
|
|
end
|
|
end
|
|
end
|
|
|
|
def execute(str = nil)
|
|
unless str.is_a?(String)
|
|
puts "Error: Expected a string but got #{str.inspect}"
|
|
return
|
|
end
|
|
|
|
str, esses = str.split(" -")
|
|
super_level = esses ? esses.count("s") : 0
|
|
source = SourceFinder.new(@irb_context).find_source(str, super_level)
|
|
|
|
if source
|
|
show_source(source)
|
|
elsif super_level > 0
|
|
puts "Error: Couldn't locate a super definition for #{str}"
|
|
else
|
|
puts "Error: Couldn't locate a definition for #{str}"
|
|
end
|
|
nil
|
|
end
|
|
|
|
private
|
|
|
|
def show_source(source)
|
|
if source.binary_file?
|
|
content = "\n#{bold('Defined in binary file')}: #{source.file}\n\n"
|
|
else
|
|
code = source.colorized_content || 'Source not available'
|
|
content = <<~CONTENT
|
|
|
|
#{bold("From")}: #{source.file}:#{source.line}
|
|
|
|
#{code.chomp}
|
|
|
|
CONTENT
|
|
end
|
|
Pager.page_content(content)
|
|
end
|
|
|
|
def bold(str)
|
|
Color.colorize(str, [:BOLD])
|
|
end
|
|
end
|
|
end
|
|
end
|