Module: MethodSource::CodeHelpers
- Included in:
- MethodSource
- Defined in:
- lib/method_source/code_helpers.rb
Defined Under Namespace
Modules: IncompleteExpression
Instance Method Summary collapse
-
#comment_describing(file, line_number) ⇒ String
Retrieve the comment describing the expression on the given line of the given file.
-
#complete_expression?(str) ⇒ Boolean
Determine if a string of code is a complete Ruby expression.
-
#expression_at(file, line_number, options = {}) ⇒ String
Retrieve the first expression starting on the given line of the given file.
Instance Method Details
#comment_describing(file, line_number) ⇒ String
Retrieve the comment describing the expression on the given line of the given file.
This is useful to get module or method documentation.
52 53 54 55 56 |
# File 'lib/method_source/code_helpers.rb', line 52 def comment_describing(file, line_number) lines = file.is_a?(Array) ? file : file.each_line.to_a extract_last_comment(lines[0..(line_number - 2)]) end |
#complete_expression?(str) ⇒ Boolean
Determine if a string of code is a complete Ruby expression.
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 |
# File 'lib/method_source/code_helpers.rb', line 66 def complete_expression?(str) old_verbose = $VERBOSE $VERBOSE = nil catch(:valid) do eval("BEGIN{throw :valid}\n#{str}") end # Assert that a line which ends with a , or \ is incomplete. str !~ /[,\\]\s*\z/ rescue IncompleteExpression false ensure $VERBOSE = old_verbose end |
#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!
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, ={}) = { :strict => false, :consume => 0 }.merge!() lines = file.is_a?(Array) ? file : file.each_line.to_a relevant_lines = lines[(line_number - 1)..-1] || [] extract_first_expression(relevant_lines, [:consume]) rescue SyntaxError => e raise if [:strict] begin extract_first_expression(relevant_lines) do |code| code.gsub(/\#\{.*?\}/, "temp") end rescue SyntaxError raise e end end |