class RuboCop::Cop::Style::BracesAroundHashParameters
if the last parameter is a hash.
This cop checks for braces around the last parameter in a method call
def add_braces(corrector, node)
def add_braces(corrector, node) corrector.insert_before(node.source_range, '{') corrector.insert_after(node.source_range, '}') end
def autocorrect(send_node)
the AST has changed, a braceless hash would not be parsed as a hash
node, because that context is needed. When parsing the code to see if
We let AutocorrectUnlessChangingAST#autocorrect work with the send
def autocorrect(send_node) _receiver, _method_name, *args = *send_node node = args.last lambda do |corrector| if node.braces? remove_braces_with_whitespace(corrector, node) else add_braces(corrector, node) end end end
def braces?(arg)
def braces?(arg) arg.loc.begin end
def check(arg, args)
def check(arg, args) if style == :braces && !arg.braces? add_offense(arg.parent, arg.source_range, format(MSG, 'Missing')) elsif style == :no_braces && arg.braces? add_offense(arg.parent, arg.source_range, format(MSG, 'Redundant')) elsif style == :context_dependent check_context_dependent(arg, args) end end
def check_context_dependent(arg, args)
def check_context_dependent(arg, args) braces_around_second_from_end = args.size > 1 && args[-2].hash_type? if arg.braces? unless braces_around_second_from_end add_offense(arg.parent, arg.source_range, format(MSG, 'Redundant')) end elsif braces_around_second_from_end add_offense(arg.parent, arg.source_range, format(MSG, 'Missing')) end end
def comment_on_line?(line)
def comment_on_line?(line) processed_source.comments.any? { |c| c.loc.line == line } end
def on_send(node)
def on_send(node) return if node.asgn_method_call? _receiver, method_name, *args = *node return if operator?(method_name) return if args.empty? return unless args.last.hash_type? && !args.last.pairs.empty? check(args.last, args) end
def remove_braces(corrector, node)
def remove_braces(corrector, node) corrector.remove(node.loc.begin) corrector.remove(node.loc.end) end
def remove_braces_with_whitespace(corrector, node)
def remove_braces_with_whitespace(corrector, node) right_brace_and_space = right_brace_and_space(node.loc.end) if comment_on_line?(right_brace_and_space.line) # Removing a line break between a comment and the closing # parenthesis would cause a syntax error, so we only remove the # braces in that case. remove_braces(corrector, node) else left_brace_and_space = range_with_surrounding_space(node.loc.begin, :right) corrector.remove(left_brace_and_space) corrector.remove(right_brace_and_space) end end
def right_brace_and_space(loc_end)
def right_brace_and_space(loc_end) brace_and_space = range_with_surrounding_space(loc_end, :left) range_with_surrounding_comma(brace_and_space, :left) end