Sha256: 8ed5cf9d505fa27530e5e7ac19aa7df549f99802c918ddc7785b7a47598833f6

Contents?: true

Size: 1.16 KB

Versions: 3

Compression:

Stored size: 1.16 KB

Contents

# encoding: utf-8

module Rubocop
  module Cop
    module Style
      # This cop checks for multi-line ternary op expressions.
      class MultilineTernaryOperator < Cop
        MSG =
          'Avoid multi-line ?: (the ternary operator); use if/unless instead.'

        def on_if(node)
          loc = node.loc

          # discard non-ternary ops
          return unless loc.respond_to?(:question)

          if loc.line != loc.colon.line
            add_offence(:convention, loc.expression, MSG)
          end

          super
        end
      end

      # This cop checks for nested ternary op expressions.
      class NestedTernaryOperator < Cop
        MSG = 'Ternary operators must not be nested. Prefer if/else ' +
            'constructs instead.'

        def on_if(node)
          loc = node.loc

          # discard non-ternary ops
          return unless loc.respond_to?(:question)

          node.children.each do |child|
            on_node(:if, child) do |c|
              if c.loc.respond_to?(:question)
                add_offence(:convention, c.loc.expression, MSG)
              end
            end
          end

          super
        end
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 2 rubygems

Version Path
rubocop-0.9.1 lib/rubocop/cop/style/ternary_operator.rb
sabat-rubocop-0.9.0 lib/rubocop/cop/style/ternary_operator.rb
rubocop-0.9.0 lib/rubocop/cop/style/ternary_operator.rb