Module: Detective

Defined in:
lib/detective.rb

Class Method Summary collapse

Class Method Details

.get_location(ruby_statement) ⇒ Object

Finds the location of a method in ruby source files You can pass a string like

  • ‘Class.name’ class method

# ‘String#size’ instance method



55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/detective.rb', line 55

def self.get_location(ruby_statement)
  if ruby_statement.index('#')
    # instance method
    class_name, method_name = ruby_statement.split('#')
    class_method = false
  elsif ruby_statement.index('.')
    class_name, method_name = ruby_statement.split('.')
    class_method = true
  else
    raise "Invalid parameter"
  end
  the_klass = eval(class_name)
  ForkSupported ? get_location_fork(the_klass, method_name, class_method) : get_location_thread(the_klass, method_name, class_method)
end

.view_source(method, format = :plain) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/detective.rb', line 12

def self.view_source(method, format=:plain)
   location = get_location(method).strip.split /[\r\n]+/
   case location.first
     when 'native method' then return 'native method'
     when 'error' then raise location[1..-1].join(' ')
     when 'location' then
     begin
       filename, line_no = location[1,2] 
       line_no = line_no.to_i
       f = File.open filename
       source = ""
       output = case format
         when :plain then ""
         when :rdoc then "#{filename}, line #{line_no}" << "\r\n"
         else ""
       end
       current_line_no = 0
       rp = RubyParser.new
       f.each_line do |current_line|
         current_line_no += 1
         if current_line_no >= line_no
           output << case format
             when :plain then current_line
             when :rdoc then "#{current_line_no}:#{current_line}"
             else current_line
           end
           source << current_line
           # Try to parse it to know whether the method is complete or not
           rp.parse(source) && break rescue nil
         end
       end
       f.close
       return output
     rescue Exception => e
       return "Cannot find source code"
     end
   end
end