summaryrefslogtreecommitdiff
path: root/lib/irb/command/show_source.rb
diff options
context:
space:
mode:
authorStan Lo <[email protected]>2024-02-16 16:47:32 +0000
committergit <[email protected]>2024-02-16 16:47:36 +0000
commitf5801e2bf404cbb0f673a6ebb040b0ba6cd01b77 (patch)
tree8ee0d5041c9d46df4448c80c28ffb929daabe4b4 /lib/irb/command/show_source.rb
parent4411cdeef9f49cc295b2456b15a14550e8d88804 (diff)
[ruby/irb] Standardize command related names
(https://github.com/ruby/irb/pull/873) * Replace ExtendCommand with Command and standardize command related names 1. Rename lib/irb/extend-command.rb to lib/irb/command.rb 2. Rename lib/irb/cmd/*.rb to lib/irb/command/*.rb 3. Rename test/irb/test_cmd.rb to test/irb/test_command.rb 4. Rename ExtendCommand to Command * Alias ExtendCommand to Command and deprecate it * Rename Command::Nop to Command::Base * Not deprecate old constants just yet * Add lib/irb/cmd/nop.rb back https://github.com/ruby/irb/commit/462c1284af
Diffstat (limited to 'lib/irb/command/show_source.rb')
-rw-r--r--lib/irb/command/show_source.rb67
1 files changed, 67 insertions, 0 deletions
diff --git a/lib/irb/command/show_source.rb b/lib/irb/command/show_source.rb
new file mode 100644
index 0000000000..cc783e7532
--- /dev/null
+++ b/lib/irb/command/show_source.rb
@@ -0,0 +1,67 @@
+# frozen_string_literal: true
+
+require_relative "../source_finder"
+require_relative "../pager"
+require_relative "../color"
+
+module IRB
+ module Command
+ class ShowSource < Base
+ 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