Sha256: 6c5a3d247e878ab7e106b703d81a9a93dad21114552100b18b6dd4004b97395a

Contents?: true

Size: 1.81 KB

Versions: 15

Compression:

Stored size: 1.81 KB

Contents

# encoding: utf-8

module RuboCop
  module Cop
    module Style
      # Use a guard clause instead of wrapping the code inside a conditional
      # expression
      #
      # @example
      #   # bad
      #   def test
      #     if something
      #       work
      #     end
      #   end
      #
      #   # good
      #   def test
      #     return unless something
      #     work
      #   end
      #
      #   # also good
      #   def test
      #     work if something
      #   end
      class GuardClause < Cop
        include ConfigurableEnforcedStyle
        include IfNode

        MSG = 'Use a guard clause instead of wrapping the code inside a ' \
              'conditional expression.'

        def on_def(node)
          _, _, body = *node
          return unless body

          if if?(body)
            check_if_node(body)
          elsif body.type == :begin
            expressions = *body
            last_expr = expressions.last

            check_if_node(last_expr) if if?(last_expr)
          end
        end

        private

        def if?(body)
          body && body.type == :if
        end

        def check_if_node(node)
          _cond, body, else_body = *node

          return if body && else_body
          # discard modifier ifs and ternary_ops
          return if modifier_if?(node) || ternary_op?(node)
          # discard short ifs
          return unless min_body_length?(node)

          add_offense(node, :keyword, MSG)
        end

        def min_body_length?(node)
          (node.loc.end.line - node.loc.keyword.line) > min_body_length
        end

        def min_body_length
          length = cop_config['MinBodyLength'] || 1
          return length if length.is_a?(Integer) && length > 0

          fail 'MinBodyLength needs to be a positive integer!'
        end
      end
    end
  end
end

Version data entries

15 entries across 15 versions & 2 rubygems

Version Path
rubyjobbuilderdsl-0.0.2 vendor/bundle/ruby/2.1.0/gems/rubocop-0.26.0/lib/rubocop/cop/style/guard_clause.rb
rubyjobbuilderdsl-0.0.1 vendor/bundle/ruby/2.1.0/gems/rubocop-0.26.0/lib/rubocop/cop/style/guard_clause.rb
rubocop-0.30.1 lib/rubocop/cop/style/guard_clause.rb
rubocop-0.30.0 lib/rubocop/cop/style/guard_clause.rb
rubocop-0.29.1 lib/rubocop/cop/style/guard_clause.rb
rubocop-0.29.0 lib/rubocop/cop/style/guard_clause.rb
rubocop-0.28.0 lib/rubocop/cop/style/guard_clause.rb
rubocop-0.27.1 lib/rubocop/cop/style/guard_clause.rb
rubocop-0.27.0 lib/rubocop/cop/style/guard_clause.rb
rubocop-0.26.1 lib/rubocop/cop/style/guard_clause.rb
rubocop-0.26.0 lib/rubocop/cop/style/guard_clause.rb
rubocop-0.25.0 lib/rubocop/cop/style/guard_clause.rb
rubocop-0.24.1 lib/rubocop/cop/style/guard_clause.rb
rubocop-0.24.0 lib/rubocop/cop/style/guard_clause.rb
rubocop-0.23.0 lib/rubocop/cop/style/guard_clause.rb