Class: IRB::SourceFinder

Inherits:
Object show all
Defined in:
lib/irb/source_finder.rb

Instance Method Summary collapse

Constructor Details

#initialize(irb_context) ⇒ SourceFinder

Returns a new instance of SourceFinder.



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

def initialize(irb_context)
  @irb_context = irb_context
end

Instance Method Details

#find_source(signature, super_level = 0) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/irb/source_finder.rb', line 19

def find_source(signature, super_level = 0)
  context_binding = @irb_context.workspace.binding
  case signature
  when /\A(::)?[A-Z]\w*(::[A-Z]\w*)*\z/ # Const::Name
    eval(signature, context_binding) # trigger autoload
    base = context_binding.receiver.yield_self { |r| r.is_a?(Module) ? r : Object }
    file, line = base.const_source_location(signature)
  when /\A(?<owner>[A-Z]\w*(::[A-Z]\w*)*)#(?<method>[^ :.]+)\z/ # Class#method
    owner = eval(Regexp.last_match[:owner], context_binding)
    method = Regexp.last_match[:method]
    return unless owner.respond_to?(:instance_method)
    file, line = method_target(owner, super_level, method, "owner")
  when /\A((?<receiver>.+)(\.|::))?(?<method>[^ :.]+)\z/ # method, receiver.method, receiver::method
    receiver = eval(Regexp.last_match[:receiver] || 'self', context_binding)
    method = Regexp.last_match[:method]
    return unless receiver.respond_to?(method, true)
    file, line = method_target(receiver, super_level, method, "receiver")
  end
  # If the line is zero, it means that the target's source is probably in a binary file, which we should ignore.
  if file && line && !line.zero? && File.exist?(file)
    Source.new(file: file, first_line: line, last_line: find_end(file, line))
  end
end