Sha256: ce9257dc427b3e696bf87e450cdf778360b7d08db8e5956e3fe9d81f53d8aa6b

Contents?: true

Size: 1.06 KB

Versions: 14

Compression:

Stored size: 1.06 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 < Cop
        include OnNormalIfUnless

        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)
        end

        def autocorrect(node)
          lambda 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

14 entries across 14 versions & 3 rubygems

Version Path
rubocop-0.89.0 lib/rubocop/cop/style/if_with_semicolon.rb
rubocop-0.88.0 lib/rubocop/cop/style/if_with_semicolon.rb
rbhint-0.87.1.rc1 lib/rubocop/cop/style/if_with_semicolon.rb
rubocop-0.87.1 lib/rubocop/cop/style/if_with_semicolon.rb
rubocop-0.87.0 lib/rubocop/cop/style/if_with_semicolon.rb
rubocop-0.86.0 lib/rubocop/cop/style/if_with_semicolon.rb
files.com-1.0.1 vendor/bundle/ruby/2.5.0/gems/rubocop-0.85.1/lib/rubocop/cop/style/if_with_semicolon.rb
rbhint-0.85.1.rc2 lib/rubocop/cop/style/if_with_semicolon.rb
rbhint-0.85.1.rc1 lib/rubocop/cop/style/if_with_semicolon.rb
rubocop-0.85.1 lib/rubocop/cop/style/if_with_semicolon.rb
rbhint-0.8.5.rc1 lib/rubocop/cop/style/if_with_semicolon.rb
rubocop-0.85.0 lib/rubocop/cop/style/if_with_semicolon.rb
rubocop-0.84.0 lib/rubocop/cop/style/if_with_semicolon.rb
rubocop-0.83.0 lib/rubocop/cop/style/if_with_semicolon.rb