From c5e33d9c11d2cfd26aa7edfa32ee565f5405b3a1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lo=C3=AFc=20Guitaut?= Date: Thu, 29 Feb 2024 16:14:26 +0100 Subject: [PATCH] FEATURE: Add autocorrect to the FabricatorShorthand cop --- .../cop/discourse/fabricator_shorthand.rb | 20 ++++++++++++++----- rubocop-discourse.gemspec | 2 +- .../rubocop/cop/fabricator_shorthand_spec.rb | 15 ++++++++++++++ 3 files changed, 31 insertions(+), 6 deletions(-) diff --git a/lib/rubocop/cop/discourse/fabricator_shorthand.rb b/lib/rubocop/cop/discourse/fabricator_shorthand.rb index 744793a..1b42d4f 100644 --- a/lib/rubocop/cop/discourse/fabricator_shorthand.rb +++ b/lib/rubocop/cop/discourse/fabricator_shorthand.rb @@ -26,9 +26,12 @@ module Discourse # # good # fab!(:another_user) { Fabricate(:user) } class FabricatorShorthand < Base + extend AutoCorrector + include IgnoredNode + def_node_matcher :offending_fabricator?, <<-MATCHER (block - (send nil? :fab! + $(send nil? :fab! (sym $_identifier)) (args) (send nil? :Fabricate @@ -36,15 +39,22 @@ class FabricatorShorthand < Base MATCHER def on_block(node) - offending_fabricator?(node) do |identifier| - add_offense(node, message: message(identifier)) + offending_fabricator?(node) do |expression, _identifier| + add_offense( + node, + message: message(expression.source) + ) do |corrector| + next if part_of_ignored_node?(node) + corrector.replace(node, expression.source) + end + ignore_node(node) end end private - def message(identifier) - "Use the fabricator shorthand: `fab!(:#{identifier})`" + def message(expression) + "Use the fabricator shorthand: `#{expression}`" end end end diff --git a/rubocop-discourse.gemspec b/rubocop-discourse.gemspec index 0d53955..4daeba9 100644 --- a/rubocop-discourse.gemspec +++ b/rubocop-discourse.gemspec @@ -2,7 +2,7 @@ Gem::Specification.new do |s| s.name = "rubocop-discourse" - s.version = "3.7.0" + s.version = "3.7.1" s.summary = "Custom rubocop cops used by Discourse" s.authors = ["Discourse Team"] s.license = "MIT" diff --git a/spec/lib/rubocop/cop/fabricator_shorthand_spec.rb b/spec/lib/rubocop/cop/fabricator_shorthand_spec.rb index 203cf23..1eec4f4 100644 --- a/spec/lib/rubocop/cop/fabricator_shorthand_spec.rb +++ b/spec/lib/rubocop/cop/fabricator_shorthand_spec.rb @@ -31,4 +31,19 @@ end RUBY end + + it "supports autocorrect" do + expect_offense(<<~RUBY) + RSpec.describe "Foo" do + fab!(:foo) { Fabricate(:foo) } + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Discourse/FabricatorShorthand: Use the fabricator shorthand: `fab!(:foo)` + end + RUBY + + expect_correction(<<~RUBY) + RSpec.describe "Foo" do + fab!(:foo) + end + RUBY + end end