From 53f7d5d0fe6745d7c4efb52cfcdaa295c77778c4 Mon Sep 17 00:00:00 2001 From: Koichi ITO Date: Fri, 15 Sep 2023 02:11:06 +0900 Subject: [PATCH] [Fix #1121] Fix an error for `Rails/SelectMap` Fixes #1121. This PR fixes an error for `Rails/SelectMap` when using `select(:column_name).map(&:column_name)` without receiver model. --- changelog/fix_an_error_for_rails_select_map.md | 1 + lib/rubocop/cop/rails/select_map.rb | 5 ++++- spec/rubocop/cop/rails/select_map_spec.rb | 11 +++++++++++ 3 files changed, 16 insertions(+), 1 deletion(-) create mode 100644 changelog/fix_an_error_for_rails_select_map.md diff --git a/changelog/fix_an_error_for_rails_select_map.md b/changelog/fix_an_error_for_rails_select_map.md new file mode 100644 index 0000000000..7eab352547 --- /dev/null +++ b/changelog/fix_an_error_for_rails_select_map.md @@ -0,0 +1 @@ +* [#1121](https://github.com/rubocop/rubocop-rails/issues/1121): Fix an error for `Rails/SelectMap` when using `select(:column_name).map(&:column_name)` without receiver model. ([@koic][]) diff --git a/lib/rubocop/cop/rails/select_map.rb b/lib/rubocop/cop/rails/select_map.rb index 54a898385a..ede846d915 100644 --- a/lib/rubocop/cop/rails/select_map.rb +++ b/lib/rubocop/cop/rails/select_map.rb @@ -51,10 +51,13 @@ def find_select_node(node, column_name) end end + # rubocop:disable Metrics/AbcSize def autocorrect(corrector, select_node, node, preferred_method) - corrector.remove(select_node.loc.dot.begin.join(select_node.source_range.end)) + corrector.remove(select_node.loc.dot || node.loc.dot) + corrector.remove(select_node.loc.selector.begin.join(select_node.source_range.end)) corrector.replace(node.loc.selector.begin.join(node.source_range.end), preferred_method) end + # rubocop:enable Metrics/AbcSize def match_column_name?(select_candidate, column_name) return false unless select_candidate.arguments.one? diff --git a/spec/rubocop/cop/rails/select_map_spec.rb b/spec/rubocop/cop/rails/select_map_spec.rb index 0ea548620e..767516e4d6 100644 --- a/spec/rubocop/cop/rails/select_map_spec.rb +++ b/spec/rubocop/cop/rails/select_map_spec.rb @@ -45,6 +45,17 @@ RUBY end + it 'registers an offense when using `select(:column_name).map(&:column_name)` without receiver model' do + expect_offense(<<~RUBY) + select(:column_name).map(&:column_name) + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use `pluck(:column_name)` instead of `select` with `map`. + RUBY + + expect_correction(<<~RUBY) + pluck(:column_name) + RUBY + end + it 'does not register an offense when using `select(:mismatch_column_name).map(&:column_name)`' do expect_no_offenses(<<~RUBY) Model.select(:mismatch_column_name).map(&:column_name)