Module: MethodSource

Defined in:
lib/method_source.rb,
lib/method_source/version.rb,
lib/method_source/source_location.rb

Defined Under Namespace

Modules: MethodExtensions, ReeSourceLocation, SourceLocation

Constant Summary

VERSION =
"0.6.8"

Class Method Summary (collapse)

Class Method Details

+ (String) comment_helper(source_location)

Helper method responsible for opening source file and buffering up the comments for a specified method. Defined here to avoid polluting Method class.



57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/method_source.rb', line 57

def self.comment_helper(source_location)
  return nil if !source_location.is_a?(Array)

  file_name, line = source_location
  File.open(file_name) do |file|
    buffer = ""
    (line - 1).times do
      line = file.readline
      # Add any line that is a valid ruby comment,
      # but clear as soon as we hit a non comment line.
      if (line =~ /^\s*#/) || (line =~ /^\s*$/)
        buffer << line.lstrip
      else
        buffer.replace("")
      end
    end

    buffer
  end
end

+ (File) source_helper(source_location)

Helper method responsible for extracting method body. Defined here to avoid polluting Method class.



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/method_source.rb', line 35

def self.source_helper(source_location)
  return nil if !source_location.is_a?(Array)

  file_name, line = source_location
  File.open(file_name) do |file|
    (line - 1).times { file.readline }

    code = ""
    loop do
      val = file.readline
      code << val

      return code if valid_expression?(code)
    end
  end
end

+ (Boolean) valid_expression?(str)

Determine if a string of code is a valid Ruby expression.

Examples:

valid_expression?("class Hello") #=> false
valid_expression?("class Hello; end") #=> true


16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/method_source.rb', line 16

def self.valid_expression?(str)
  if defined?(Rubinius::Melbourne19) && RUBY_VERSION =~ /^1\.9/
    Rubinius::Melbourne19.parse_string(str)
  elsif defined?(Rubinius::Melbourne)
    Rubinius::Melbourne.parse_string(str)
  else
    catch(:valid) {
      eval("BEGIN{throw :valid}\n#{str}")
    }
  end
  true
rescue SyntaxError
  false
end