diff --git a/changelog/fix_an_error_for_rails_read_write_attribute_cop.md b/changelog/fix_an_error_for_rails_read_write_attribute_cop.md new file mode 100644 index 0000000000..1cb346bc5a --- /dev/null +++ b/changelog/fix_an_error_for_rails_read_write_attribute_cop.md @@ -0,0 +1 @@ +* [#1488](https://github.com/rubocop/rubocop-rails/issues/1488): Fix an error for `Rails/ReadWriteAttribute` with a frozen string attribute name. ([@viralpraxis][]) diff --git a/lib/rubocop/cop/rails/read_write_attribute.rb b/lib/rubocop/cop/rails/read_write_attribute.rb index b3c30aba3a..a89842ffef 100644 --- a/lib/rubocop/cop/rails/read_write_attribute.rb +++ b/lib/rubocop/cop/rails/read_write_attribute.rb @@ -66,7 +66,7 @@ def within_shadowing_method?(node) return false unless enclosing_method shadowing_method_name = first_arg.value.to_s - shadowing_method_name << '=' if node.method?(:write_attribute) + shadowing_method_name += '=' if node.method?(:write_attribute) enclosing_method.method?(shadowing_method_name) end diff --git a/spec/rubocop/cop/rails/read_write_attribute_spec.rb b/spec/rubocop/cop/rails/read_write_attribute_spec.rb index da5eb396a1..4d83715688 100644 --- a/spec/rubocop/cop/rails/read_write_attribute_spec.rb +++ b/spec/rubocop/cop/rails/read_write_attribute_spec.rb @@ -235,6 +235,21 @@ def foo=(value) RUBY end + it 'corrects assignment with chained methods when using string attribute name' do + expect_offense(<<~RUBY) + def attr2=(k) + write_attribute("attr", 'test_' + postfix) + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Prefer `self["attr"] = 'test_' + postfix`. + end + RUBY + + expect_correction(<<~RUBY) + def attr2=(k) + self["attr"] = 'test_' + postfix + end + RUBY + end + it 'autocorrects multiline' do expect_offense(<<~RUBY) write_attribute(