Sha256: a43d9e3c4b749fb4e3caac522ec20fd65eea2c7f885a339bc673423d5f3eb511

Contents?: true

Size: 1.32 KB

Versions: 11

Compression:

Stored size: 1.32 KB

Contents

# frozen_string_literal: true

module RuboCop
  module Cop
    module Style
      # This cop checks for nested ternary op expressions.
      #
      # @example
      #   # bad
      #   a ? (b ? b1 : b2) : a2
      #
      #   # good
      #   if a
      #     b ? b1 : b2
      #   else
      #     a2
      #   end
      class NestedTernaryOperator < Base
        extend AutoCorrector

        MSG = 'Ternary operators must not be nested. Prefer `if` or `else` ' \
              'constructs instead.'

        def on_if(node)
          return unless node.ternary?

          node.each_descendant(:if).select(&:ternary?).each do |nested_ternary|
            add_offense(nested_ternary) do |corrector|
              if_node = if_node(nested_ternary)

              corrector.replace(if_node, <<~RUBY.chop)
                if #{if_node.condition.source}
                  #{remove_parentheses(if_node.if_branch.source)}
                else
                  #{if_node.else_branch.source}
                end
              RUBY
            end
          end
        end

        private

        def if_node(node)
          node = node.parent
          return node if node.if_type?

          if_node(node)
        end

        def remove_parentheses(source)
          source.gsub(/\A\(/, '').gsub(/\)\z/, '')
        end
      end
    end
  end
end

Version data entries

11 entries across 11 versions & 3 rubygems

Version Path
plaid-14.13.0 vendor/bundle/ruby/3.0.0/gems/rubocop-0.91.1/lib/rubocop/cop/style/nested_ternary_operator.rb
plaid-14.12.1 vendor/bundle/ruby/3.0.0/gems/rubocop-0.91.1/lib/rubocop/cop/style/nested_ternary_operator.rb
plaid-14.12.0 vendor/bundle/ruby/2.6.0/gems/rubocop-0.91.1/lib/rubocop/cop/style/nested_ternary_operator.rb
plaid-14.11.1 vendor/bundle/ruby/2.6.0/gems/rubocop-0.91.1/lib/rubocop/cop/style/nested_ternary_operator.rb
plaid-14.10.0 vendor/bundle/ruby/2.6.0/gems/rubocop-0.91.1/lib/rubocop/cop/style/nested_ternary_operator.rb
plaid-14.7.0 vendor/bundle/ruby/2.6.0/gems/rubocop-0.91.1/lib/rubocop/cop/style/nested_ternary_operator.rb
rubocop-0.92.0 lib/rubocop/cop/style/nested_ternary_operator.rb
rubocop-0.91.1 lib/rubocop/cop/style/nested_ternary_operator.rb
rubocop-0.91.0 lib/rubocop/cop/style/nested_ternary_operator.rb
grape-extra_validators-2.0.0 vendor/bundle/ruby/2.6.0/gems/rubocop-0.90.0/lib/rubocop/cop/style/nested_ternary_operator.rb
rubocop-0.90.0 lib/rubocop/cop/style/nested_ternary_operator.rb