Module: RuboCop::NodePattern::Macros
- Included in:
- Astrolabe::Node, Cop::Cop, Cop::SafeAssignment, Cop::Style::ParallelAssignment::AssignmentSorter
- Defined in:
- lib/rubocop/node_pattern.rb
Overview
Helpers for defining methods based on a pattern string
Instance Method Summary collapse
-
#def_node_matcher(method_name, pattern_str) ⇒ Object
Define a method which applies a pattern to an AST node.
-
#def_node_search(method_name, pattern_str) ⇒ Object
Define a method which recurses over the descendants of an AST node, checking whether any of them match the provided pattern.
Instance Method Details
#def_node_matcher(method_name, pattern_str) ⇒ Object
Define a method which applies a pattern to an AST node
The new method will return nil if the node does not match
If the node matches, and a block is provided, the new method will
yield to the block (passing any captures as block arguments).
If the node matches, and no block is provided, the new method will
return the captures, or true
if there were none.
344 345 346 347 348 349 |
# File 'lib/rubocop/node_pattern.rb', line 344 def def_node_matcher(method_name, pattern_str) compiler = RuboCop::NodePattern::Compiler.new(pattern_str, 'node') src = "def #{method_name}(node" << compiler.emit_trailing_param_list << ');' << compiler.emit_method_code << ';end' class_eval(src) end |
#def_node_search(method_name, pattern_str) ⇒ Object
Define a method which recurses over the descendants of an AST node, checking whether any of them match the provided pattern
If the method name ends with '?', the new method will return true
as soon as it finds a descendant which matches. Otherwise, it will
yield all descendants which match.
357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 |
# File 'lib/rubocop/node_pattern.rb', line 357 def def_node_search(method_name, pattern_str) compiler = RuboCop::NodePattern::Compiler.new(pattern_str, 'node') if method_name.to_s.end_with?('?') on_match = 'return true' prelude = '' else yieldval = compiler.emit_capture_list yieldval = 'node' if yieldval.empty? on_match = "yield(#{yieldval})" prelude = "return enum_for(:#{method_name},node0) unless block_given?" end src = <<-END def #{method_name}(node0#{compiler.emit_trailing_param_list}) #{prelude} node0.each_node do |node| if #{compiler.match_code} #{on_match} end end nil end END class_eval(src) end |