class RuboCop::Cop::ParenthesesCorrector
This autocorrects parentheses
Constants
- COMMA_REGEXP
Public Class Methods
Source
# File lib/rubocop/cop/correctors/parentheses_corrector.rb, line 12 def correct(corrector, node) buffer = node.source_range.source_buffer corrector.remove(range_with_surrounding_space(range: node.loc.begin, buffer: buffer, side: :right, whitespace: true)) corrector.remove(range_with_surrounding_space(range: node.loc.end, buffer: buffer, side: :left)) handle_orphaned_comma(corrector, node) return unless ternary_condition?(node) && next_char_is_question_mark?(node) corrector.insert_after(node.loc.end, ' ') end
Private Class Methods
Source
# File lib/rubocop/cop/correctors/parentheses_corrector.rb, line 77 def add_heredoc_comma(corrector, node) return unless heredoc?(node) corrector.insert_after(node.child_nodes.last, ',') end
Add a comma back after the heredoc identifier
Source
# File lib/rubocop/cop/correctors/parentheses_corrector.rb, line 67 def extend_range_for_heredoc(node, range) return range unless heredoc?(node) comma_line = range_by_whole_lines(node.loc.end, buffer: node.source_range.source_buffer) offset = comma_line.source.match(COMMA_REGEXP)[0]&.size || 0 range.adjust(end_pos: offset) end
If the node contains a heredoc, remove the comma too It’ll be added back in the right place later
Source
# File lib/rubocop/cop/correctors/parentheses_corrector.rb, line 44 def handle_orphaned_comma(corrector, node) return unless only_closing_paren_before_comma?(node) range = extend_range_for_heredoc(node, parens_range(node)) corrector.remove(range) add_heredoc_comma(corrector, node) end
If removing parentheses leaves a comma on its own line, remove all the whitespace preceding it to prevent a syntax error.
Source
# File lib/rubocop/cop/correctors/parentheses_corrector.rb, line 83 def heredoc?(node) node.child_nodes.last.loc.is_a?(Parser::Source::Map::Heredoc) end
Source
# File lib/rubocop/cop/correctors/parentheses_corrector.rb, line 31 def next_char_is_question_mark?(node) node.loc.last_column == node.parent.loc.question.column end
Source
# File lib/rubocop/cop/correctors/parentheses_corrector.rb, line 35 def only_closing_paren_before_comma?(node) source_buffer = node.source_range.source_buffer line_range = source_buffer.line_range(node.loc.end.line) line_range.source.start_with?(/\s*\)\s*,/) end
Source
# File lib/rubocop/cop/correctors/parentheses_corrector.rb, line 54 def parens_range(node) range_with_surrounding_space( range: node.loc.end, buffer: node.source_range.source_buffer, side: :left, newlines: true, whitespace: true, continuations: true ) end
Get a range for the closing parenthesis and all whitespace to the left of it
Source
# File lib/rubocop/cop/correctors/parentheses_corrector.rb, line 27 def ternary_condition?(node) node.parent&.if_type? && node.parent.ternary? end