Skip to content

Commit

Permalink
Merge pull request #373 from fatkodima/fix-ar_callbacks_order-inline-…
Browse files Browse the repository at this point in the history
…comments

Fix an infinite loop error for `Rails/ActiveRecordCallbacksOrder` when callbacks have inline comments
  • Loading branch information
koic committed Oct 19, 2020
2 parents 1117cd0 + 4e5563b commit 46661ea
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 2 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Expand Up @@ -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)
Expand Down
6 changes: 5 additions & 1 deletion lib/rubocop/cop/rails/active_record_callbacks_order.rb
Expand Up @@ -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
Expand All @@ -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
Expand Down
18 changes: 17 additions & 1 deletion spec/rubocop/cop/rails/active_record_callbacks_order_spec.rb
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down

0 comments on commit 46661ea

Please sign in to comment.