Method: MethodSource::CodeHelpers#expression_at

Defined in:
lib/method_source/code_helpers.rb

#expression_at(file, line_number, options = {}) ⇒ String

Retrieve the first expression starting on the given line of the given file.

This is useful to get module or method source code.

                      line 1!

Parameters:

  • file (Array<String>, File, String)

    The file to parse, either as a File or as

  • line_number (Integer)

    The line number at which to look. NOTE: The first line in a file is

  • options (Hash) (defaults to: {})

    The optional configuration parameters.

Options Hash (options):

  • :strict (Boolean)

    If set to true, then only completely valid expressions are returned. Otherwise heuristics are used to extract expressions that may have been valid inside an eval.

  • :consume (Integer)

    A number of lines to automatically consume (add to the expression buffer) without checking for validity.

Returns:

  • (String)

    The first complete expression

Raises:

  • (SyntaxError)

    If the first complete expression can't be identified



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

def expression_at(file, line_number, options={})
  options = {
    :strict  => false,
    :consume => 0
  }.merge!(options)

  lines = file.is_a?(Array) ? file : file.each_line.to_a

  relevant_lines = lines[(line_number - 1)..-1] || []

  extract_first_expression(relevant_lines, options[:consume])
rescue SyntaxError => e
  raise if options[:strict]

  begin
    extract_first_expression(relevant_lines) do |code|
      code.gsub(/\#\{.*?\}/, "temp")
    end
  rescue SyntaxError
    raise e
  end
end