Sha256: 5f0e2d22e3d1c9f4c90ee60e2cbbcfb3a8a634320bff7bc097fb0b50d19ed072

Contents?: true

Size: 1.44 KB

Versions: 10

Compression:

Stored size: 1.44 KB

Contents

# 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

        source = SourceFinder.new(@irb_context).find_source(str)

        if source
          show_source(source)
        else
          puts "Error: Couldn't locate a definition for #{str}"
        end
        nil
      end

      private

      def show_source(source)
        file_content = IRB::Color.colorize_code(File.read(source.file))
        code = file_content.lines[(source.first_line - 1)...source.last_line].join
        content = <<~CONTENT

          #{bold("From")}: #{source.file}:#{source.first_line}

          #{code}
        CONTENT

        Pager.page_content(content)
      end

      def bold(str)
        Color.colorize(str, [:BOLD])
      end
    end
  end
end

Version data entries

10 entries across 10 versions & 2 rubygems

Version Path
study_line-0.1.6 vendor/bundle/ruby/3.2.0/gems/irb-1.8.3/lib/irb/cmd/show_source.rb
study_line-0.1.5 vendor/bundle/ruby/3.2.0/gems/irb-1.8.3/lib/irb/cmd/show_source.rb
study_line-0.1.4 vendor/bundle/ruby/3.2.0/gems/irb-1.8.3/lib/irb/cmd/show_source.rb
study_line-0.1.3 vendor/bundle/ruby/3.2.0/gems/irb-1.8.3/lib/irb/cmd/show_source.rb
study_line-0.1.2 vendor/bundle/ruby/3.2.0/gems/irb-1.8.3/lib/irb/cmd/show_source.rb
study_line-0.1.1 vendor/bundle/ruby/3.2.0/gems/irb-1.8.3/lib/irb/cmd/show_source.rb
irb-1.9.1 lib/irb/cmd/show_source.rb
irb-1.9.0 lib/irb/cmd/show_source.rb
irb-1.8.3 lib/irb/cmd/show_source.rb
irb-1.8.2 lib/irb/cmd/show_source.rb