From 087e0ccb72e7a1491701dd1d1d49746f745d9d68 Mon Sep 17 00:00:00 2001 From: Daniel Colson Date: Tue, 17 Apr 2018 08:37:35 -0400 Subject: Add RuboCop for `assert_not` over `assert !` We added `assert_not` in f75addd "to replace warty 'assert !foo'". fa8d35b agrees that it is warty, and so do I. This custom Rubocop rule turns the wart into a violation. As with my last custom cop, https://github.com/rails/rails/pull/32441, I want to make sure this looks right on code climate before pushing another commit to autocorrect everything. @toshimaru I just noticed https://github.com/toshimaru/rubocop-rails/pull/26 Is there a better way to add these custom cops, or were you saying we shouldn't have custom cops at all? --- ci/custom_cops/lib/custom_cops.rb | 1 + ci/custom_cops/lib/custom_cops/assert_not.rb | 40 ++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+) create mode 100644 ci/custom_cops/lib/custom_cops/assert_not.rb (limited to 'ci/custom_cops/lib') diff --git a/ci/custom_cops/lib/custom_cops.rb b/ci/custom_cops/lib/custom_cops.rb index d5d17f8856..157b8247e4 100644 --- a/ci/custom_cops/lib/custom_cops.rb +++ b/ci/custom_cops/lib/custom_cops.rb @@ -1,3 +1,4 @@ # frozen_string_literal: true require_relative "custom_cops/refute_not" +require_relative "custom_cops/assert_not" diff --git a/ci/custom_cops/lib/custom_cops/assert_not.rb b/ci/custom_cops/lib/custom_cops/assert_not.rb new file mode 100644 index 0000000000..e722448e21 --- /dev/null +++ b/ci/custom_cops/lib/custom_cops/assert_not.rb @@ -0,0 +1,40 @@ +# frozen_string_literal: true + +module CustomCops + # Enforces the use of `assert_not` over `assert !`. + # + # @example + # # bad + # assert !x + # assert ! x + # + # # good + # assert_not x + # + class AssertNot < RuboCop::Cop::Cop + MSG = "Prefer `assert_not` over `assert !`" + + def_node_matcher :offensive?, "(send nil? :assert (send ... :!))" + + def on_send(node) + add_offense(node) if offensive?(node) + end + + def autocorrect(node) + expression = node.loc.expression + + ->(corrector) do + corrector.replace( + expression, + corrected_source(expression.source) + ) + end + end + + private + + def corrected_source(source) + source.gsub(/^assert(\(| ) *! */, "assert_not\\1") + end + end +end -- cgit v1.2.3