Sha256: 4c22fd84b5b1f7ee6fdb3d9400b336eb0f7f252c9969710e1d48d8b04c61768f

Contents?: true

Size: 1.03 KB

Versions: 22

Compression:

Stored size: 1.03 KB

Contents

# frozen_string_literal: true

module RuboCop
  module Cop
    module Style
      # Checks for uses of semicolon in if statements.
      #
      # @example
      #
      #   # bad
      #   result = if some_condition; something else another_thing end
      #
      #   # good
      #   result = some_condition ? something : another_thing
      #
      class IfWithSemicolon < Base
        include OnNormalIfUnless
        extend AutoCorrector

        MSG = 'Do not use if x; Use the ternary operator instead.'

        def on_normal_if_unless(node)
          return unless node.else_branch

          beginning = node.loc.begin
          return unless beginning&.is?(';')

          add_offense(node) do |corrector|
            corrector.replace(node, correct_to_ternary(node))
          end
        end

        private

        def correct_to_ternary(node)
          else_code = node.else_branch ? node.else_branch.source : 'nil'

          "#{node.condition.source} ? #{node.if_branch.source} : #{else_code}"
        end
      end
    end
  end
end

Version data entries

22 entries across 22 versions & 3 rubygems

Version Path
plaid-14.13.0 vendor/bundle/ruby/3.0.0/gems/rubocop-0.91.1/lib/rubocop/cop/style/if_with_semicolon.rb
plaid-14.12.1 vendor/bundle/ruby/3.0.0/gems/rubocop-0.91.1/lib/rubocop/cop/style/if_with_semicolon.rb
plaid-14.12.0 vendor/bundle/ruby/2.6.0/gems/rubocop-0.91.1/lib/rubocop/cop/style/if_with_semicolon.rb
plaid-14.11.1 vendor/bundle/ruby/2.6.0/gems/rubocop-0.91.1/lib/rubocop/cop/style/if_with_semicolon.rb
plaid-14.10.0 vendor/bundle/ruby/2.6.0/gems/rubocop-0.91.1/lib/rubocop/cop/style/if_with_semicolon.rb
plaid-14.7.0 vendor/bundle/ruby/2.6.0/gems/rubocop-0.91.1/lib/rubocop/cop/style/if_with_semicolon.rb
rubocop-1.4.2 lib/rubocop/cop/style/if_with_semicolon.rb
rubocop-1.4.1 lib/rubocop/cop/style/if_with_semicolon.rb
rubocop-1.4.0 lib/rubocop/cop/style/if_with_semicolon.rb
rubocop-1.3.1 lib/rubocop/cop/style/if_with_semicolon.rb
rubocop-1.3.0 lib/rubocop/cop/style/if_with_semicolon.rb
rubocop-1.2.0 lib/rubocop/cop/style/if_with_semicolon.rb
rubocop-1.1.0 lib/rubocop/cop/style/if_with_semicolon.rb
rubocop-1.0.0 lib/rubocop/cop/style/if_with_semicolon.rb
rubocop-0.93.1 lib/rubocop/cop/style/if_with_semicolon.rb
rubocop-0.93.0 lib/rubocop/cop/style/if_with_semicolon.rb
rubocop-0.92.0 lib/rubocop/cop/style/if_with_semicolon.rb
rubocop-0.91.1 lib/rubocop/cop/style/if_with_semicolon.rb
rubocop-0.91.0 lib/rubocop/cop/style/if_with_semicolon.rb
grape-extra_validators-2.0.0 vendor/bundle/ruby/2.6.0/gems/rubocop-0.90.0/lib/rubocop/cop/style/if_with_semicolon.rb