Skip to content

Commit

Permalink
[Fix rubocop#6722] Fix an error for Style/OneLineConditional
Browse files Browse the repository at this point in the history
Fixes rubocop#6722.

This PR fixes an error for `Style/OneLineConditional` when
`then` branch has no body. The following is an error case.

```ruby
# example.rb
if cond then else dont end
```

The following is a reproduction step.

```console
% rubocop -v
0.63.1

% rubocop -a example.rb --only Style/OneLineConditional
Inspecting 1 file

0 files inspected, no offenses detected
undefined method `type' for nil:NilClass
/Users/koic/.rbenv/versions/2.6.1/lib/ruby/gems/2.6.0/gems/rubocop-0.63.1/lib/rubocop/cop/style/one_line_conditional.rb:74:in
`requires_parentheses?'
/Users/koic/.rbenv/versions/2.6.1/lib/ruby/gems/2.6.0/gems/rubocop-0.63.1/lib/rubocop/cop/style/one_line_conditional.rb:70:in
`expr_replacement'
/Users/koic/.rbenv/versions/2.6.1/lib/ruby/gems/2.6.0/gems/rubocop-0.63.1/lib/rubocop/cop/style/one_line_conditional.rb:65:in
`to_ternary'

(snip)
```

This PR auto-corrected to the following code.

```ruby
cond ? nil : dont
```

Actually the above code is the same behavior as `unless` modifier.
But this PR aims auto-corrected to an equivalent code without causing an error.
  • Loading branch information
koic committed Feb 4, 2019
1 parent a0f8c22 commit 3998094
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 0 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Expand Up @@ -16,6 +16,7 @@
* [#6668](https://github.com/rubocop-hq/rubocop/issues/6668): Fix autocorrection for `Style/UnneededCondition` when conditional has the `unless` form. ([@mvz][])
* [#6382](https://github.com/rubocop-hq/rubocop/issues/6382): Fix `Layout/IndentationWidth` with `Layout/EndAlignment` set to start_of_line. ([@dischorde][], [@siegfault][], [@mhelmetag][])
* [#6710](https://github.com/rubocop-hq/rubocop/issues/6710): Fix `Naming/MemoizedInstanceVariableName` on method starts with underscore. ([@pocke][])
* [#6722](https://github.com/rubocop-hq/rubocop/issues/6722): Fix an error for `Style/OneLineConditional` when `then` branch has no body. ([@koic][])

### Changes

Expand Down
2 changes: 2 additions & 0 deletions lib/rubocop/cop/style/one_line_conditional.rb
Expand Up @@ -67,6 +67,8 @@ def to_ternary(node)
end

def expr_replacement(node)
return 'nil' if node.nil?

requires_parentheses?(node) ? "(#{node.source})" : node.source
end

Expand Down
7 changes: 7 additions & 0 deletions spec/rubocop/cop/style/one_line_conditional_spec.rb
Expand Up @@ -38,6 +38,13 @@
end
end

context 'one line if/then/else/end when `then` branch has no body' do
let(:source) { 'if cond then else dont end' }

include_examples 'offense', 'if'
include_examples 'autocorrect', 'cond ? nil : dont'
end

context 'one line if/then/end' do
let(:source) { 'if cond then run end' }

Expand Down

0 comments on commit 3998094

Please sign in to comment.