Sha256: acc4afc6dd0a59aee83124151eb0a7d95f0470cc9325fd4c7fa3156db3bf5797

Contents?: true

Size: 1.37 KB

Versions: 24

Compression:

Stored size: 1.37 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)
          return source unless source.start_with?('(')

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

Version data entries

24 entries across 24 versions & 1 rubygems

Version Path
rubocop-1.12.1 lib/rubocop/cop/style/nested_ternary_operator.rb
rubocop-1.12.0 lib/rubocop/cop/style/nested_ternary_operator.rb
rubocop-1.11.0 lib/rubocop/cop/style/nested_ternary_operator.rb
rubocop-1.10.0 lib/rubocop/cop/style/nested_ternary_operator.rb
rubocop-1.9.1 lib/rubocop/cop/style/nested_ternary_operator.rb
rubocop-1.9.0 lib/rubocop/cop/style/nested_ternary_operator.rb
rubocop-1.8.1 lib/rubocop/cop/style/nested_ternary_operator.rb
rubocop-1.8.0 lib/rubocop/cop/style/nested_ternary_operator.rb
rubocop-1.7.0 lib/rubocop/cop/style/nested_ternary_operator.rb
rubocop-1.6.1 lib/rubocop/cop/style/nested_ternary_operator.rb
rubocop-1.6.0 lib/rubocop/cop/style/nested_ternary_operator.rb
rubocop-1.5.2 lib/rubocop/cop/style/nested_ternary_operator.rb
rubocop-1.5.1 lib/rubocop/cop/style/nested_ternary_operator.rb
rubocop-1.5.0 lib/rubocop/cop/style/nested_ternary_operator.rb
rubocop-1.4.2 lib/rubocop/cop/style/nested_ternary_operator.rb
rubocop-1.4.1 lib/rubocop/cop/style/nested_ternary_operator.rb
rubocop-1.4.0 lib/rubocop/cop/style/nested_ternary_operator.rb
rubocop-1.3.1 lib/rubocop/cop/style/nested_ternary_operator.rb
rubocop-1.3.0 lib/rubocop/cop/style/nested_ternary_operator.rb
rubocop-1.2.0 lib/rubocop/cop/style/nested_ternary_operator.rb