Skip to content

Commit

Permalink
Merge pull request #9917 from jonas054/9848_fix_ClassStructure
Browse files Browse the repository at this point in the history
[Fix #9848] Handle EOL comments in ClassStructure auto-correct
  • Loading branch information
koic committed Jul 7, 2021
2 parents a2fcc3d + caf12fa commit 3d21b60
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 1 deletion.
1 change: 1 addition & 0 deletions changelog/fix_class_structure_eol_comment_bug.md
@@ -0,0 +1 @@
* [#9848](https://github.com/rubocop/rubocop/issues/9848): Fix handling of comments in `Layout/ClassStructure` auto-correct. ([@jonas054][])
6 changes: 5 additions & 1 deletion lib/rubocop/cop/layout/class_structure.rb
Expand Up @@ -289,12 +289,16 @@ def begin_pos_with_comment(node)
(node.first_line - 1).downto(1) do |annotation_line|
break unless (comment = processed_source.comment_at_line(annotation_line))

first_comment = comment
first_comment = comment if whole_line_comment_at_line?(annotation_line)
end

start_line_position(first_comment || node)
end

def whole_line_comment_at_line?(line)
/\A\s*#/.match?(processed_source.lines[line - 1])
end

def start_line_position(node)
buffer.line_range(node.loc.line).begin_pos - 1
end
Expand Down
19 changes: 19 additions & 0 deletions spec/rubocop/cop/layout/class_structure_spec.rb
Expand Up @@ -39,6 +39,25 @@
)
end

context 'when the first line ends with a comment' do
it 'reports an offense and swaps the lines' do
expect_offense <<-RUBY
class GridTask
DESC = 'Grid Task' # grid task name OID, subclasses should set this
extend Helpers::MakeFromFile
^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `module_inclusion` is supposed to appear before `constants`.
end
RUBY

expect_correction <<-RUBY
class GridTask
extend Helpers::MakeFromFile
DESC = 'Grid Task' # grid task name OID, subclasses should set this
end
RUBY
end
end

context 'with a complete ordered example' do
it 'does not create offense' do
expect_no_offenses <<-RUBY
Expand Down

0 comments on commit 3d21b60

Please sign in to comment.