Skip to content

Commit

Permalink
[Fix rubocop#9606] Fix an error for Layout/IndentationConsistency
Browse files Browse the repository at this point in the history
Fixes rubocop#9606.

This PR fixes the following error for `Layout/IndentationConsistency`
when using access modifier at the top level.

```console
% cat example.rb
public

def foo
end

% bundle exec rubocop --only Layout/IndentationConsistency example.rb -d
(snip)

Scanning /Users/koic/src/github.com/koic/rubocop-issues/9606/example.rb
An error occurred while Layout/IndentationConsistency cop was inspecting
/Users/koic/src/github.com/koic/rubocop-issues/9606/example.rb:1:0.
undefined method `source_range' for nil:NilClass
/Users/koic/src/github.com/rubocop/rubocop/lib/rubocop/cop/layout/indentation_consistency.rb:165:in
`base_column_for_normal_style'
/Users/koic/src/github.com/rubocop/rubocop/lib/rubocop/cop/layout/indentation_consistency.rb:181:in
`check_normal_style'
/Users/koic/src/github.com/rubocop/rubocop/lib/rubocop/cop/layout/indentation_consistency.rb:174:in
`check'
/Users/koic/src/github.com/rubocop/rubocop/lib/rubocop/cop/layout/indentation_consistency.rb:129:in
`on_begin'
```
  • Loading branch information
koic committed Mar 16, 2021
1 parent d69aaae commit f0260b6
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 1 deletion.
1 change: 1 addition & 0 deletions changelog/fix_error_for_layout_indentation_consistency.md
@@ -0,0 +1 @@
* [#9606](https://github.com/rubocop/rubocop/issues/9606): Fix an error for `Layout/IndentationConsistency` when using access modifier at the top level. ([@koic][])
4 changes: 3 additions & 1 deletion lib/rubocop/cop/layout/indentation_consistency.rb
Expand Up @@ -162,8 +162,10 @@ def base_column_for_normal_style(node)
# to the level of the module (see `AccessModifierIndentation` cop) we
# return nil so that `check_alignment` will derive the correct
# indentation from the first child that is not an access modifier.
module_indent = display_column(node.parent.source_range)
access_modifier_indent = display_column(first_child.source_range)
return access_modifier_indent unless node.parent

module_indent = display_column(node.parent.source_range)
access_modifier_indent if access_modifier_indent > module_indent
end

Expand Down
27 changes: 27 additions & 0 deletions spec/rubocop/cop/layout/indentation_consistency_spec.rb
Expand Up @@ -9,6 +9,33 @@
"#{}"
RUBY
end

it 'accepts when using access modifier at the top level' do
expect_no_offenses(<<~'RUBY')
public
def foo
end
RUBY
end

it 'registers and corrects an offense when using access modifier and dedented method definition ' \
'at the top level' do
expect_offense(<<~'RUBY')
public
def foo
^^^^^^^ Inconsistent indentation detected.
end
RUBY

expect_correction(<<~'RUBY')
public
def foo
end
RUBY
end
end

context 'with if statement' do
Expand Down

0 comments on commit f0260b6

Please sign in to comment.