Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add new Lint/LiteralAssignmentInCondition cop #12420

Commits on Nov 29, 2023

  1. Add new Lint/LiteralAssignmentInCondition cop

    ## Summary
    
    This PR adds a new `Lint/LiteralAssignmentInCondition` cop, which checks for
    literal assignments in the conditions of `if`, `while`, and `until`.
    It emulates the following Ruby warning:
    
    ```console
    $ ruby -we 'if x = true; end'
    -e:1: warning: found `= literal' in conditional, should be ==
    ```
    
    As a lint cop, it cannot be determined if `==` is appropriate as intended,
    therefore this cop does not provide autocorrection.
    
    ```ruby
    # bad
    if x = 42
      do_something
    end
    
    # good
    if x == 42
      do_something
    end
    
    # good
    if x = y
      do_something
    end
    ```
    
    Literal assignment used within a condition always triggers a Ruby warning, regardless of parentheses.
    This PR prevents the Ruby warning from being overlooked due to the `ruby -w` option.
    
    ## Additional Information
    
    Here, the differences between similar cops, `Lint/LiteralAssignmentInCondition` cop and
    `Lint/LiteralAsCondition` cop are discussed.
    
    ### `Lint/LiteralAssignmentInCondition` cop
    
    A similar `Lint/LiteralAssignmentInCondition` cop already exists, but as mentioned above,
    literal assignments are Ruby's warned about regardless of the presence of parentheses:
    
    ```ruby
    $ ruby -we 'if (x = 42); end'
    -e:1: warning: found `= literal' in conditional, should be ==
    ```
    
    Therefore, a new cop has been created separate from `Lint/LiteralAssignmentInCondition`.
    
    Furthermore, as documented for `Lint/LiteralAssignmentInCondition` cop, literal assignments
    are never considered `good` case, so `= true` has been replaced with `= value`.
    
    ### `Lint/LiteralAsCondition` cop
    
    Additionally, the existing `Lint/LiteralAsCondition` cop addresses a slightly different Ruby warning:
    
    ```ruby
    $ ruby -we 'if 42; end'
    -e:1: warning: literal in condition
    ```
    
    This is another reason for choosing to implement a new cop.
    koic committed Nov 29, 2023
    Configuration menu
    Copy the full SHA
    0ca08b3 View commit details
    Browse the repository at this point in the history