Sha256: cf5014128aa1dc724cc8896cf27fc182a8663ca04766c6928437335940f0a3e5

Contents?: true

Size: 1.66 KB

Versions: 3

Compression:

Stored size: 1.66 KB

Contents

# encoding: utf-8
# frozen_string_literal: true

module RuboCop
  module Cop
    # Common functionality for modifier cops.
    module StatementModifier
      include IfNode

      def fit_within_line_as_modifier_form?(node)
        cond, body, _else = if_node_parts(node)

        return false if length(node) > 3
        return false if body && body.begin_type? # multiple statements

        body_length = body_length(body)

        return false if body_length.zero?
        return false if cond.each_node.any?(&:lvasgn_type?)
        return false if body_has_comment?(body)
        return false if end_keyword_has_comment?(node)

        length_in_modifier_form(node, cond, body_length) <= max_line_length
      end

      def length_in_modifier_form(node, cond, body_length)
        indentation = node.loc.keyword.column
        kw_length = node.loc.keyword.size
        cond_length = cond.source_range.size
        space = 1
        indentation + body_length + space + kw_length + space + cond_length
      end

      def max_line_length
        cop_config['MaxLineLength'] ||
          config.for_cop('Metrics/LineLength')['Max']
      end

      def length(node)
        node.source.lines.grep(/\S/).size
      end

      def body_length(body)
        if body && body.source_range
          body.source_range.size
        else
          0
        end
      end

      def body_has_comment?(body)
        comment_lines.include?(body.source_range.line)
      end

      def end_keyword_has_comment?(node)
        comment_lines.include?(node.loc.end.line)
      end

      def comment_lines
        @comment_lines ||= processed_source.comments.map { |c| c.location.line }
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 2 rubygems

Version Path
fluent-plugin-detect-memb-exceptions-0.0.2 vendor/bundle/ruby/2.0.0/gems/rubocop-0.42.0/lib/rubocop/cop/mixin/statement_modifier.rb
fluent-plugin-detect-memb-exceptions-0.0.1 vendor/bundle/ruby/2.0.0/gems/rubocop-0.42.0/lib/rubocop/cop/mixin/statement_modifier.rb
rubocop-0.42.0 lib/rubocop/cop/mixin/statement_modifier.rb