> ## Documentation Index
> Fetch the complete documentation index at: https://docs.codeant.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Ruby

<AccordionGroup>
  <Accordion title="Related if/elsif statements and when in a case should not have the same condition">
    <div class="paragraph">
      <p>A \`case and a chain of if/elsif statements is evaluated from top to bottom. At most, only one branch will be executed: the first one with a condition that evaluates to true.</p>
    </div>

    <div class="paragraph">
      <p>Therefore, duplicating a condition automatically leads to dead code. Usually, this is due to a copy/paste error. At best, it’s simply dead code and at worst, it’s a bug that is likely to induce further bugs as the code is maintained, and obviously it could lead to unexpected behavior.</p>
    </div>

    <div class="paragraph">
      <p>For a case, the second when\` will never be executed, rendering it dead code. Worse there is the risk in this situation that future maintenance will be done on the dead case, rather than on the one that’s actually used.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```ruby Bad theme={null}
      if param == 1
      openWindow()
      elsif param == 2
      closeWindow()
      elsif param == 1  # Noncompliant
      moveWindowToTheBackground()
      end

      case i
      when 1
      # ...
      when 3
      # ...
      when 1  # Noncompliant
      # ...
      else
      # ...
      end
      ```

      ```ruby Fix theme={null}
      if param == 1
      openWindow()
      elsif param == 2
      closeWindow()
      elsif param == 3
      moveWindowToTheBackground()
      end

      case i
      when 1
      # ...
      when 3
      # ...
      else
      # ...
      end
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="All code should be reachable">
    <div class="paragraph">
      <p>Jump statements (<code>return, break and next</code>) move control flow out of the current code block. So any statements that come after a jump are dead code.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```ruby Bad theme={null}
      def foo(a)
      i = 10
      return a + i    # Noncompliant 
      i += 1          # dead code
      end
      ```

      ```ruby Fix theme={null}
      def foo(a)
      i = 10
      return a + i
      end
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="if ... else if constructs should end with else clauses">
    <div class="paragraph">
      <p>This rule applies whenever an \`if statement is followed by one or more elsif statements; the final elsif should be followed by an else statement.</p>
    </div>

    <div class="paragraph">
      <p>The requirement for a final else statement is defensive programming.</p>
    </div>

    <div class="paragraph">
      <p>The else statement should either take appropriate action or contain a suitable comment as to why no action is taken. This is consistent with the requirement to have a final else clause in a case\` statement.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```ruby Bad theme={null}
      if x == 0                                      
      doSomething
      elsif x == 1
      doSomethingElse
      end
      ```

      ```ruby Fix theme={null}
      if x == 0                                      
      doSomething
      elsif x == 1
      doSomethingElse
      else
      raise 'An error has occured'
      end
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Method names should comply with a naming convention">
    <div class="paragraph">
      <p>Shared naming conventions allow teams to collaborate efficiently.</p>
    </div>

    <div class="paragraph">
      <p>This rule raises an issue when a method name does not match a provided regular expression.</p>
    </div>

    <div class="paragraph">
      <p>For example, with the default provided regular expression, the following method:</p>
    </div>

    <CodeGroup>
      ```ruby Bad theme={null}
      def methodName # Noncompliant
      expr..
      end
      ```

      ```ruby Fix theme={null}
      def method_name
      expr..
      end
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="case when clauses should not have too many lines of code">
    <div class="paragraph">
      <p>The <code>case statement should be used only to clearly define some new branches in the control flow. As soon as a when</code> clause contains too many statements this highly decreases the readability of the overall control flow statement. In such case, the content of the case clause should be extracted into a dedicated function.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```ruby Bad theme={null}
      case myVariable
      when 0 then # Noncompliant: 6 lines till next "when"
      methodCall1("")
      methodCall2("")
      methodCall3("")
      methodCall4("")
      methodCall5("")
      methodCall6("")
      when 1
      # ...
      end
      ```

      ```ruby Fix theme={null}
      case myVariable
      when 0 then
      doSomething()
      when 1
      # ...
      end
      ...
      def doSomething()
      methodCall1("")
      methodCall2("")
      methodCall3("")
      methodCall4("")
      methodCall5("")
      methodCall6("")
      end
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="All branches in a conditional structure should not have exactly the same implementation">
    <div class="paragraph">
      <p>Having all branches of a case or if chain with the same implementation indicates a problem.</p>
    </div>

    <div class="paragraph">
      <p>In the following code:</p>
    </div>

    <CodeGroup>
      ```ruby Bad theme={null}
      if b == 0  # Noncompliant
      doOneMoreThing()
      else
      doOneMoreThing()
      end

      b = a > 12 ? 4 : 4;  # Noncompliant

      case i  # Noncompliant
      when 1
      doSomething()
      when 2
      doSomething()
      when 3
      doSomething()
      else 
      doSomething()
      end
      ```

      ```ruby Fix theme={null}
      if b == 0 # no issue, this could have been done on purpose to make the code more readable
      doSomething()
      elsif b == 1
      doSomething()
      end
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="case statements should have else clauses">
    <div class="paragraph">
      <p>The requirement for a final <code>else</code> clause is defensive programming. The clause should either take appropriate action, or contain a suitable comment as to why no action is taken.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```ruby Bad theme={null}
      case param
      when 1
      do_something()
      when 2
      do_something_else()
      end
      ```

      ```ruby Fix theme={null}
      case param
      when 1
      do_something()
      when 2
      do_something_else()
      else
      handle_error('error_message')
      end
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="case statements should not be nested">
    <div class="paragraph">
      <p>Nested \`case structures are difficult to understand because you can easily confuse the cases of an inner case as belonging to an outer statement. Therefore nested case statements should be avoided.</p>
    </div>

    <div class="paragraph">
      <p>Specifically, you should structure your code to avoid the need for nested case statements, but if you cannot, then consider moving the inner case\` to another function.</p>
    </div>

    <div class="paragraph" />

    <CodeGroup>
      ```ruby Bad theme={null}
      def foo(n, m)
      case n
      when 0
        case m  # Noncompliant; nested case
        when 0 then puts "0"
          # ...
        end
      when 1 then puts "1"
      else puts "2"
      end
      end
      ```

      ```ruby Fix theme={null}
      def foo(n, m)
      case n
      when 0
      bar(m)
      when 1 then puts "1"
      else puts "2"
      end
      end

      def bar(m)
      case m
      when 0 then puts "0"
      # ...
      end
      end
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Boolean checks should not be inverted">
    <div class="paragraph">
      <p>It is needlessly complex to invert the result of a boolean comparison. The opposite comparison should be made instead.</p>
    </div>

    <CodeGroup>
      ```ruby Bad theme={null}
      if  !(a == 2)  # Noncompliant
      # ...
      end

      b = !(a < 10) # Noncompliant
      ```

      ```ruby Fix theme={null}
      if a != 2
      # ...
      end
      b = (a >= 10)
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Statements should be on separate lines">
    <div class="paragraph">
      <p>Putting multiple statements on a single line lowers the code readability and makes debugging the code more complex.</p>
    </div>

    <div class="paragraph">
      <p>Unresolved directive in \<stdin> - include::\{noncompliant}\[]</p>
    </div>

    <div class="paragraph">
      <p>Write one statement per line to improve readability.</p>
    </div>

    <div class="paragraph">
      <p>Unresolved directive in \<stdin> - include::\{compliant}\[]</p>
    </div>

    <CodeGroup>
      ```ruby Bad theme={null}
      if someCondition; puts "hello"; end # Noncompliant
      ```

      ```ruby Fix theme={null}
      if someCondition
      puts "hello"
      end
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Expressions should not be too complex">
    <div class="paragraph">
      <p>The complexity of an expression is defined by the number of <code>&&, || and condition ? ifTrue : ifFalse</code> operators it contains.</p>
    </div>

    <div class="paragraph">
      <p>A single expression’s complexity should not become too high to keep the code readable.</p>
    </div>

    <CodeGroup>
      ```ruby Bad theme={null}
      if ((condition1 && condition2) || (condition3 && condition4)) && condition5
      ...
      end
      ```

      ```ruby Fix theme={null}
      if (myFirstCondition() || mySecondCondition()) && myLastCondition()
      ...
      end
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Octal values should not be used">
    <div class="paragraph">
      <p>Integer literals starting with a zero are octal rather than decimal values. While using octal values is fully supported, most developers do not have experience with them. They may not recognize octal values as such, mistaking them instead for decimal values.</p>
    </div>

    <CodeGroup>
      ```ruby Bad theme={null}
      my_number = 023 # Noncompliant. my_number will hold 19, not 23 - was this really expected?
      ```

      ```ruby Fix theme={null}
      my_number = 23
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Mergeable if statements should be combined">
    <div class="paragraph">
      <p>Nested code - blocks of code inside blocks of code - is eventually necessary, but increases complexity. This is why keeping the code as flat as possible, by avoiding unnecessary nesting, is considered a good practice.</p>
    </div>

    <div class="paragraph">
      <p>Merging if statements when possible will decrease the nesting of the code and improve its readability.</p>
    </div>

    <CodeGroup>
      ```ruby Bad theme={null}
      if a then
      unless b then  # Noncompliant
      # ...
      end
      end
      ```

      ```ruby Fix theme={null}
      if a && !b then  # Compliant
      # ...
      end
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Methods should not be empty">
    <div class="paragraph">
      <p>An empty \{operationName} is generally considered bad practice and can lead to confusion, readability, and maintenance issues.
      Empty \{operationName}s bring no functionality and are misleading to others as they might think the \{operationName} implementation fulfills a specific and identified requirement.</p>
    </div>

    <div class="paragraph">
      <p>There are several reasons for a \{operationName} not to have a body:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>It is an unintentional omission, and should be fixed to prevent an unexpected behavior in production.</p>
        </li>

        <li>
          <p>It is not yet, or never will be, supported. In this case an exception should be thrown.</p>
        </li>

        <li>
          <p>The method is an intentionally-blank override. In this case a nested comment should explain the reason for the blank override.</p>
        </li>
      </ul>
    </div>

    <CodeGroup>
      ```ruby Bad theme={null}
      def shouldNotBeEmpty()  # Noncompliant - method is empty
      end

      def notImplemented()  # Noncompliant - method is empty
      end

      def emptyOnPurpose()  # Noncompliant - method is empty
      end
      ```

      ```ruby Fix theme={null}
      def shouldNotBeEmpty()
      doSomething()
      end

      def notImplemented()
      raise NotImplementedError, 'notImplemented() cannot be performed because ...'
      end

      def emptyOnPurpose()
      # comment explaining why the method is empty
      end
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Track lack of copyright and license headers">
    <div class="paragraph">
      <p>Each source file should start with a header stating file ownership and the license which must be used to distribute the application.</p>
    </div>

    <div class="paragraph">
      <p>This rule must be fed with the header text that is expected at the beginning of every file.</p>
    </div>

    <CodeGroup>
      ```ruby Bad theme={null}
      #
      # SonarQube, open source software quality management tool.
      # Copyright (C) 2008-2018 SonarSource
      # mailto:contact AT sonarsource DOT com
      #
      # SonarQube is free software; you can redistribute it and/or
      # modify it under the terms of the GNU Lesser General Public
      # License as published by the Free Software Foundation; either
      # version 3 of the License, or (at your option) any later version.
      #
      # SonarQube is distributed in the hope that it will be useful,
      # but WITHOUT ANY WARRANTY; without even the implied warranty of
      # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
      # Lesser General Public License for more details.
      #
      # You should have received a copy of the GNU Lesser General Public License
      # along with this program; if not, write to the Free Software Foundation,
      # Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
      #
      ```

      ```ruby Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Redundant pairs of parentheses should be removed">
    <div class="paragraph">
      <p>The use of parentheses, even those not required to enforce a desired order of operations, can clarify the intent behind a piece of code. However, redundant pairs of parentheses could be misleading and should be removed.</p>
    </div>

    <CodeGroup>
      ```ruby Bad theme={null}
      x = (y / 2 + 1)  # Compliant even if the parenthesis are ignored by the compiler

      if a && ((x+y > 0))  # Noncompliant
      # ...
      end

      return ((x + 1)) # Noncompliant
      ```

      ```ruby Fix theme={null}
      x = (y / 2 + 1)

      if a && (x+y > 0)
      # ...
      end

      return (x + 1)
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Class names should comply with a naming convention">
    <div class="paragraph">
      <p>Shared naming conventions allow teams to collaborate efficiently.</p>
    </div>

    <div class="paragraph">
      <p>This rule raises an issue when a class name does not match a provided regular expression.</p>
    </div>

    <CodeGroup>
      ```ruby Bad theme={null}
      class my_class # Noncompliant
      ...
      end
      ```

      ```ruby Fix theme={null}
      class MyClass
      ...
      end
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Variables should not be self-assigned">
    <div class="paragraph">
      <p>There is no reason to re-assign a variable to itself. Either this statement is redundant and should be removed, or the re-assignment is a mistake and some other value or variable was intended for the assignment instead.</p>
    </div>

    <CodeGroup>
      ```ruby Bad theme={null}
      def set_name(name)
      name = name
      end
      ```

      ```ruby Fix theme={null}
      def set_name(name)
      @name = name
      end
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="String literals should not be duplicated">
    <div class="paragraph">
      <p>Duplicated string literals make the process of refactoring complex and error-prone, as any change would need to be propagated on all occurrences.</p>
    </div>

    <CodeGroup>
      ```ruby Bad theme={null}
      def foo()
      prepare('action random1')    #Noncompliant - "action random1" is duplicated 3 times
      execute('action random1')
      release('action random1')
      end
      ```

      ```ruby Fix theme={null}
      def foo()
      ACTION1 = 'action random1'
      prepare(ACTION1)
      execute(ACTION1)
      release(ACTION1)
      end
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Methods should not have identical implementations">
    <div class="paragraph">
      <p>Two \{func\_name}s having the same implementation are suspicious.
      It might be that something else was intended. Or the duplication is intentional, which becomes a maintenance burden.</p>
    </div>

    <CodeGroup>
      ```ruby Bad theme={null}
      class Circle
      def initialize(radius)
      @radius = radius
      end

      def width=(size)
      @radius = size / 2
      update_shape()
      end

      def height=(size) # Noncompliant: duplicates width
      @radius = size / 2
      update_shape()
      end

      def updateShape()
      ...
      end
      end
      ```

      ```ruby Fix theme={null}
      class Circle
      def initialize(radius)
      @radius = radius
      end

      def width=(width)
      self.diameter = width
      end

      def height=(height)
      self.diameter = height
      end

      def diameter=(diameter)  # Implementation is shared
      @radius = diameter / 2
      update_shape()
      end

      def update_shape()
      # ...
      end
      end
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Using hardcoded IP addresses is security-sensitive">
    <div class="paragraph">
      <p>Hardcoding IP addresses is security-sensitive. It has led in the past to the following vulnerabilities:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p><a href="http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2006-5901">CVE-2006-5901</a></p>
        </li>

        <li>
          <p><a href="http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2005-3725">CVE-2005-3725</a></p>
        </li>
      </ul>
    </div>

    <div class="paragraph">
      <p>Today’s services have an ever-changing architecture due to their scaling and redundancy needs. It is a mistake to think that a service will always have the same IP address. When it does change, the hardcoded IP will have to be modified too. This will have an impact on the product development, delivery, and deployment:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>The developers will have to do a rapid fix every time this happens, instead of having an operation team change a configuration file.</p>
        </li>

        <li>
          <p>It misleads to use the same address in every environment (dev, sys, qa, prod).</p>
        </li>
      </ul>
    </div>

    <div class="paragraph">
      <p>Last but not least it has an effect on application security. Attackers might be able to decompile the code and thereby discover a potentially sensitive address. They can perform a Denial of Service attack on the service, try to get access to the system, or try to spoof the IP address to bypass security checks. Such attacks can always be possible, but in the case of a hardcoded IP address solving the issue will take more time, which will increase an attack’s impact.</p>
    </div>

    <CodeGroup>
      ```ruby Bad theme={null}
      ip = IP_ADDRESS; // Compliant
      ```

      ```ruby Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Track uses of TODO tags">
    <div class="paragraph">
      <p>Developers often use TODO tags to mark areas in the code where additional work or improvements are needed but are not implemented immediately.
      However, these TODO tags sometimes get overlooked or forgotten, leading to incomplete or unfinished code.
      This rule aims to identify and address unattended TODO tags to ensure a clean and maintainable codebase.
      This description explores why this is a problem and how it can be fixed to improve the overall code quality.</p>
    </div>

    <CodeGroup>
      ```ruby Bad theme={null}
      def do_something()
      # TODO
      end
      ```

      ```ruby Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Useless if true ... and if false ... blocks should be removed">
    <div class="paragraph">
      <p>\`if statements with conditions that are always false have the effect of making blocks of code non-functional. if statements with conditions that are always true are completely redundant, and make the code less readable.</p>
    </div>

    <div class="paragraph">
      <p>There are three possible causes for the presence of such code:</p>
    </div>

    <div class="ulist">
      <ul>
        <li>
          <p>An if statement was changed during debugging and that debug code has been committed.</p>
        </li>

        <li>
          <p>Some value was left unset.</p>
        </li>

        <li>
          <p>Some logic is not doing what the programmer thought it did.</p>
        </li>
      </ul>
    </div>

    <div class="paragraph">
      <p>In any of these cases, unconditional if\` statements should be removed.</p>
    </div>

    <CodeGroup>
      ```ruby Bad theme={null}
      if true 
      doSomething()
      end
      ...
      if false 
      doSomethingElse()
      end
      ```

      ```ruby Fix theme={null}
      doSomething()
      ...
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Nested blocks of code should not be left empty">
    <div class="paragraph">
      <p>An empty code block is confusing. It will require some effort from maintainers to determine if it is intentional or indicates the implementation is incomplete.</p>
    </div>

    <div class="paragraph">
      <p>Unresolved directive in \<stdin> - include::\{example}\[]</p>
    </div>

    <div class="paragraph">
      <p>Removing or filling the empty code blocks takes away ambiguity and generally results in a more straightforward and less surprising code.</p>
    </div>

    <CodeGroup>
      ```ruby Bad theme={null}
      while @order.process_next; end # Compliant by exception
      ```

      ```ruby Fix theme={null}
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Unused local variables should be removed">
    <div class="paragraph">
      <p>An unused local variable is a variable that has been declared but is not used anywhere in the block of code where it is defined. It is dead code, contributing to unnecessary complexity and leading to confusion when reading the code. Therefore, it should be removed from your code to maintain clarity and efficiency.</p>
    </div>

    <CodeGroup>
      ```ruby Bad theme={null}
      def number_of_minutes(hours)
      seconds = 0 # Noncompliant - seconds is unused
      hours * 60
      end
      ```

      ```ruby Fix theme={null}
      def number_of_minutes(hours)
      hours * 60
      end
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Function and block parameter names should comply with a naming convention">
    <div class="paragraph">
      <p>A naming convention in software development is a set of guidelines for naming code elements like variables, functions, and classes.
      \{identifier\_capital\_plural} hold the meaning of the written code. Their names should be meaningful and follow a consistent and easily recognizable pattern.
      Adhering to a consistent naming convention helps to make the code more readable and understandable, which makes it easier to maintain and debug.
      It also ensures consistency in the code, especially when multiple developers are working on the same project.</p>
    </div>

    <div class="paragraph">
      <p>This rule checks that \{identifier} names match a provided regular expression.</p>
    </div>

    <CodeGroup>
      ```ruby Bad theme={null}
      def show_something(text_Param) # Noncompliant
      localVar = "" # Noncompliant
      puts text_Param + localVar
      end
      ```

      ```ruby Fix theme={null}
      def show_something(text_param)
      local_var = ""
      puts text_param + local_var
      end
      ```
    </CodeGroup>
  </Accordion>

  <Accordion title="Two branches in a conditional structure should not have exactly the same implementation">
    <div class="paragraph">
      <p>Having two when clauses in a case statement or two branches in an if chain with the same implementation is at best duplicate code, and at worst a coding error.</p>
    </div>

    <CodeGroup>
      ```ruby Bad theme={null}
      if a >= 0 && a < 10
      doFirstThing()
      doTheThing()
      elsif a >= 10 && a < 20
      doTheOtherThing()
      elsif a >= 20 && a < 50
      doFirstThing()
      doTheThing()   # Noncompliant; duplicates first condition
      else
      doTheRest()
      end
      ```

      ```ruby Fix theme={null}
      if (a >= 0 && a < 10) || (a >= 20 && a < 50)
      doFirstThing()
      doTheThing()
      elsif a >= 10 && a < 20
      doTheOtherThing()
      else
      doTheRest()
      end
      ```
    </CodeGroup>
  </Accordion>
</AccordionGroup>
