diff --git a/CHANGELOG.md b/CHANGELOG.md index f5132e3142..3e1a284726 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ ### Bug fixes +* [#371](https://github.com/rubocop-hq/rubocop-rails/pull/371): Fix an infinite loop error for `Rails/ActiveRecordCallbacksOrder` when callbacks have inline comments. ([@fatkodima][]) * [#364](https://github.com/rubocop-hq/rubocop-rails/pull/364): Fix a problem that `Rails/UniqueValidationWithoutIndex` doesn't work in classes defined with compact style. ([@sinsoku][]) ## 2.8.1 (2020-09-16) diff --git a/lib/rubocop/cop/rails/active_record_callbacks_order.rb b/lib/rubocop/cop/rails/active_record_callbacks_order.rb index d04e64d050..f1286970e3 100644 --- a/lib/rubocop/cop/rails/active_record_callbacks_order.rb +++ b/lib/rubocop/cop/rails/active_record_callbacks_order.rb @@ -121,7 +121,7 @@ def begin_pos_with_comment(node) processed_source.comments_before_line(annotation_line) .reverse_each do |comment| - if comment.location.line == annotation_line + if comment.location.line == annotation_line && !inline_comment?(comment) first_comment = comment annotation_line -= 1 end @@ -130,6 +130,10 @@ def begin_pos_with_comment(node) start_line_position(first_comment || node) end + def inline_comment?(comment) + !comment_line?(comment.loc.expression.source_line) + end + def start_line_position(node) buffer.line_range(node.loc.line).begin_pos - 1 end diff --git a/spec/rubocop/cop/rails/active_record_callbacks_order_spec.rb b/spec/rubocop/cop/rails/active_record_callbacks_order_spec.rb index 3821f94a5b..a529a3a8ff 100644 --- a/spec/rubocop/cop/rails/active_record_callbacks_order_spec.rb +++ b/spec/rubocop/cop/rails/active_record_callbacks_order_spec.rb @@ -37,7 +37,7 @@ def some_method RUBY end - it 'correcly autocorrects when there is a comment for callback method' do + it 'correcly autocorrects when there is a preceding comment for callback method' do new_source = autocorrect_source(<<~RUBY) class User < ApplicationRecord # This is a @@ -65,6 +65,22 @@ class User < ApplicationRecord RUBY end + it 'correcly autocorrects when there is an inline comment for callback method' do + new_source = autocorrect_source(<<~RUBY) + class User < ApplicationRecord + after_commit :after_commit_callback # after_commit inline comment + after_save :after_save_callback # after_save inline comment + end + RUBY + + expect(new_source).to eq(<<~RUBY) + class User < ApplicationRecord + after_save :after_save_callback # after_save inline comment + after_commit :after_commit_callback # after_commit inline comment + end + RUBY + end + it 'correcly autocorrects when there are multiple callbacks of the same type' do new_source = autocorrect_source(<<~RUBY) class User < ApplicationRecord