Sha256: c91411ac1566f04bb7d29eb3f6b7d8926a0fd2af9a5d3ecd862cc3b2d6deeade

Contents?: true

Size: 1.5 KB

Versions: 13

Compression:

Stored size: 1.5 KB

Contents

# encoding: utf-8

module Rubocop
  module Cop
    module IfThenElse
      def inspect(file, source, tokens, sexp)
        tokens.each_with_index do |t, ix|
          if t.type == :on_kw && ['if', 'unless'].include?(t.text)
            if kind_of_if(tokens, ix + 1) == self.class
              add_offence(:convention, t.pos.lineno, error_message)
            end
          end
        end
      end

      def kind_of_if(tokens, ix)
        then_found = false
        tokens[ix..-1].each do |t|
          case t.type
          when :on_kw
            case t.text
            when 'then' then then_found = true
            when 'end'  then return OneLineConditional
            end
          when :on_ignored_nl, :on_nl
            break
          when :on_semicolon
            return IfWithSemicolon
          when :on_comment
            break if t.text =~ /\n/
          when :on_sp
            nil
          else
            then_found = false
          end
        end
        then_found ? MultilineIfThen : nil
      end
    end

    class IfWithSemicolon < Cop
      include IfThenElse
      def error_message
        'Never use if x; Use the ternary operator instead.'
      end
    end

    class MultilineIfThen < Cop
      include IfThenElse
      def error_message
        'Never use then for multi-line if/unless.'
      end
    end

    class OneLineConditional < Cop
      include IfThenElse
      def error_message
        'Favor the ternary operator (?:) over if/then/else/end constructs.'
      end
    end
  end
end

Version data entries

13 entries across 13 versions & 1 rubygems

Version Path
rubocop-0.6.1 lib/rubocop/cop/if_then_else.rb
rubocop-0.6.0 lib/rubocop/cop/if_then_else.rb
rubocop-0.5.0 lib/rubocop/cop/if_then_else.rb
rubocop-0.4.6 lib/rubocop/cop/if_then_else.rb
rubocop-0.4.5 lib/rubocop/cop/if_then_else.rb
rubocop-0.4.4 lib/rubocop/cop/if_then_else.rb
rubocop-0.4.3 lib/rubocop/cop/if_then_else.rb
rubocop-0.4.2 lib/rubocop/cop/if_then_else.rb
rubocop-0.4.1 lib/rubocop/cop/if_then_else.rb
rubocop-0.4.0 lib/rubocop/cop/if_then_else.rb
rubocop-0.3.2 lib/rubocop/cop/if_then_else.rb
rubocop-0.3.1 lib/rubocop/cop/if_then_else.rb
rubocop-0.3.0 lib/rubocop/cop/if_then_else.rb