diff --git a/CHANGELOG.md b/CHANGELOG.md index c1e3971d35a..ba29ba5995e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/lib/rubocop/cop/style/one_line_conditional.rb b/lib/rubocop/cop/style/one_line_conditional.rb index 51751979734..1abda984106 100644 --- a/lib/rubocop/cop/style/one_line_conditional.rb +++ b/lib/rubocop/cop/style/one_line_conditional.rb @@ -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 diff --git a/spec/rubocop/cop/style/one_line_conditional_spec.rb b/spec/rubocop/cop/style/one_line_conditional_spec.rb index 34b066c21e1..34012ca227d 100644 --- a/spec/rubocop/cop/style/one_line_conditional_spec.rb +++ b/spec/rubocop/cop/style/one_line_conditional_spec.rb @@ -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' }