Skip to content

Commit

Permalink
Fix move namespaced constant in Style/ConditionalAssignment
Browse files Browse the repository at this point in the history
Fix autocorrect for moving constant assignment outside the condition
when the constant is in a namespace, e.g. from:

```ruby
condition ? FOO::BAR = 1 : FOO::BAR = 2

if condition
  ::FOO = 1
else
  ::FOO = 2
end
```

to keep the namespace `Foo::` and the top-level `::` in correction:

```ruby
FOO::BAR = cond? ? 1 : 2

::FOO = if condition
  1
else
  2
end
```
  • Loading branch information
biinari committed Jul 14, 2020
1 parent a500463 commit e3bcf91
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 1 deletion.
1 change: 1 addition & 0 deletions CHANGELOG.md
Expand Up @@ -5,6 +5,7 @@
### Bug fixes

* [#8324](https://github.com/rubocop-hq/rubocop/issues/8324): Fix crash for `Layout/SpaceAroundMethodCallOperator` when using `Proc#call` shorthand syntax. ([@fatkodima][])
* [#8332](https://github.com/rubocop-hq/rubocop/pull/8332): Fix auto-correct in `Style/ConditionalAssignment` to preserve constant namespace. ([@biinari][])

## 0.88.0 (2020-07-13)

Expand Down
11 changes: 10 additions & 1 deletion lib/rubocop/cop/style/conditional_assignment.rb
Expand Up @@ -43,7 +43,7 @@ def lhs(node)
when :and_asgn, :or_asgn
"#{node.children[0].source} #{node.loc.operator.source} "
when :casgn
"#{node.children[1]} = "
lhs_for_casgn(node)
when *ConditionalAssignment::VARIABLE_ASSIGNMENT_TYPES
"#{node.children[0]} = "
else
Expand Down Expand Up @@ -93,6 +93,15 @@ def lhs_for_send(node)
end
end

def lhs_for_casgn(node)
namespace = node.children[0]
if namespace.nil? || namespace.cbase_type?
"#{namespace&.source}#{node.children[1]} = "
else
"#{namespace.source}::#{node.children[1]} = "
end
end

def setter_method?(method_name)
method_name.to_s.end_with?(EQUAL) &&
!%i[!= == === >= <=].include?(method_name)
Expand Down
Expand Up @@ -1563,6 +1563,44 @@
end
end

context 'constant assignment' do
it 'corrects if..else with namespaced constant' do
expect_offense(<<~RUBY)
if something
^^^^^^^^^^^^ Use the return of the conditional for variable assignment and comparison.
FOO::BAR = 1
else
FOO::BAR = 2
end
RUBY
expect_correction(<<~RUBY)
FOO::BAR = if something
1
else
2
end
RUBY
end

it 'corrects if..else with top-level constant' do
expect_offense(<<~RUBY)
if something
^^^^^^^^^^^^ Use the return of the conditional for variable assignment and comparison.
::BAR = 1
else
::BAR = 2
end
RUBY
expect_correction(<<~RUBY)
::BAR = if something
1
else
2
end
RUBY
end
end

context 'self.attribute= assignment' do
it 'corrects if..else' do
expect_offense(<<~RUBY)
Expand Down

0 comments on commit e3bcf91

Please sign in to comment.