Module: MethodSource

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

Defined Under Namespace

Modules: MethodExtensions

Constant Summary collapse

VERSION =
"0.2.0"

Class Method Summary collapse

Class Method Details

.comment_helper(source_location) ⇒ String

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

Parameters:

  • source_location (Array)

    The array returned by Method#source_location

Returns:

  • (String)

    The comments up to the point of the method.



51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/method_source.rb', line 51

def self.comment_helper(source_location)
  return nil if !source_location.is_a?(Array)
  
  file_name, line = source_location
  file = File.open(file_name)
  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.clear
    end
  end
  
  buffer
ensure
  file.close if file
end

.source_helper(source_location) ⇒ File

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

Parameters:

  • source_location (Array)

    The array returned by Method#source_location

Returns:

  • (File)

    The opened source file



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/method_source.rb', line 27

def self.source_helper(source_location)
  return nil if !source_location.is_a?(Array)
  
  file_name, line = source_location
  file = File.open(file_name)
  (line - 1).times { file.readline }

  code = ""
  loop do
    val = file.readline
    code << val
    
    return code if MethodSource.valid_expression?(code)
  end
  
ensure
  file.close if file
end

.valid_expression?(code) ⇒ Boolean

Helper method used to find end of method body correctness

Parameters:

  • code (String)

    The string of Ruby code to check for

Returns:

  • (Boolean)


19
20
21
# File 'lib/method_source.rb', line 19

def self.valid_expression?(code)
  !!Ripper::SexpBuilder.new(code).parse
end