Class: RuboCop::Cop::Style::EvalWithLocation
- Inherits:
-
Base
- Object
- Base
- RuboCop::Cop::Style::EvalWithLocation
- Extended by:
- AutoCorrector
- Defined in:
- lib/rubocop/cop/style/eval_with_location.rb
Overview
Ensures that eval methods (‘eval`, `instance_eval`, `class_eval` and `module_eval`) are given filename and line number values (`_FILE_` and `_LINE_`). This data is used to ensure that any errors raised within the evaluated code will be given the correct identification in a backtrace.
The cop also checks that the line number given relative to ‘_LINE_` is correct.
This cop will autocorrect incorrect or missing filename and line number values. However, if ‘eval` is called without a binding argument, the cop will not attempt to automatically add a binding, or add filename and line values.
NOTE: This cop works only when a string literal is given as a code string. No offense is reported if a string variable is given as below:
- source,ruby
code = <<-RUBY
def do_something end
RUBY eval code # not checked.
Constant Summary collapse
- MSG =
'Pass `__FILE__` and `__LINE__` to `%<method_name>s`.'
- MSG_EVAL =
'Pass a binding, `__FILE__`, and `__LINE__` to `eval`.'
- MSG_INCORRECT_FILE =
'Incorrect file for `%<method_name>s`; ' \ 'use `%<expected>s` instead of `%<actual>s`.'
- MSG_INCORRECT_LINE =
'Incorrect line number for `%<method_name>s`; ' \ 'use `%<expected>s` instead of `%<actual>s`.'
- RESTRICT_ON_SEND =
i[eval class_eval module_eval instance_eval].freeze
Instance Method Summary collapse
- #line_with_offset?(node, sign, num) ⇒ Object
- #on_send(node) ⇒ Object
- #valid_eval_receiver?(node) ⇒ Object
Methods included from AutoCorrector
Instance Method Details
#line_with_offset?(node, sign, num) ⇒ Object
75 76 77 78 79 80 |
# File 'lib/rubocop/cop/style/eval_with_location.rb', line 75 def_node_matcher :line_with_offset?, "{\n (send #special_line_keyword? %1 (int %2))\n (send (int %2) %1 #special_line_keyword?)\n}\n" |
#on_send(node) ⇒ Object
82 83 84 85 86 87 88 89 90 91 92 |
# File 'lib/rubocop/cop/style/eval_with_location.rb', line 82 def on_send(node) # Classes should not redefine eval, but in case one does, it shouldn't # register an offense. Only `eval` without a receiver and `Kernel.eval` # are considered. return if node.method?(:eval) && !valid_eval_receiver?(node.receiver) code = node.first_argument return unless code&.type?(:str, :dstr) check_location(node, code) end |
#valid_eval_receiver?(node) ⇒ Object
70 71 72 |
# File 'lib/rubocop/cop/style/eval_with_location.rb', line 70 def_node_matcher :valid_eval_receiver?, "{ nil? (const {nil? cbase} :Kernel) }\n" |