diff --git a/changelog/change_mark_rails_index_with_as_unsafe.md b/changelog/change_mark_rails_index_with_as_unsafe.md new file mode 100644 index 0000000000..97631970a7 --- /dev/null +++ b/changelog/change_mark_rails_index_with_as_unsafe.md @@ -0,0 +1 @@ +* [#1463](https://github.com/rubocop/rubocop-rails/pull/1463): Mark `Rails/IndexWith` as unsafe autocorrect. ([@tejasbubane][]) diff --git a/config/default.yml b/config/default.yml index cd1a0e9833..6dab61fce2 100644 --- a/config/default.yml +++ b/config/default.yml @@ -647,8 +647,9 @@ Rails/IndexBy: Rails/IndexWith: Description: 'Prefer `index_with` over `each_with_object`, `to_h`, or `map`.' Enabled: true + SafeAutoCorrect: false VersionAdded: '2.5' - VersionChanged: '2.8' + VersionChanged: '<>' Rails/Inquiry: Description: "Prefer Ruby's comparison operators over Active Support's `Array#inquiry` and `String#inquiry`." diff --git a/lib/rubocop/cop/rails/index_with.rb b/lib/rubocop/cop/rails/index_with.rb index fc72c51646..337f09c4f6 100644 --- a/lib/rubocop/cop/rails/index_with.rb +++ b/lib/rubocop/cop/rails/index_with.rb @@ -8,6 +8,10 @@ module Rails # an enumerable into a hash where the keys are the original elements. # Rails provides the `index_with` method for this purpose. # + # This cop is marked as unsafe autocorrection, because `nil.to_h` returns {} + # but `nil.with_index` throws `NoMethodError`. Therefore, autocorrection is not + # compatible if the receiver is nil. + # # @example # # bad # [1, 2, 3].each_with_object({}) { |el, h| h[el] = foo(el) }