Module: RuboCop::Cop::StatementModifier

Includes:
IfNode
Included in:
RuboCop::Cop::Style::IfUnlessModifier, RuboCop::Cop::Style::WhileUntilModifier
Defined in:
lib/rubocop/cop/mixin/statement_modifier.rb

Overview

Common functionality for modifier cops.

Instance Method Summary collapse

Methods included from IfNode

#elsif?, #if_else?, #if_node_parts, #modifier_if?, #ternary_op?

Instance Method Details

#body_has_comment?(body) ⇒ Boolean

Returns:

  • (Boolean)

49
50
51
# File 'lib/rubocop/cop/mixin/statement_modifier.rb', line 49

def body_has_comment?(body)
  comment_lines.include?(body.loc.expression.line)
end

#body_length(body) ⇒ Object


41
42
43
44
45
46
47
# File 'lib/rubocop/cop/mixin/statement_modifier.rb', line 41

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

#comment_linesObject


57
58
59
# File 'lib/rubocop/cop/mixin/statement_modifier.rb', line 57

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

#end_keyword_has_comment?(node) ⇒ Boolean

Returns:

  • (Boolean)

53
54
55
# File 'lib/rubocop/cop/mixin/statement_modifier.rb', line 53

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

#fit_within_line_as_modifier_form?(node) ⇒ Boolean

Returns:

  • (Boolean)

9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/rubocop/cop/mixin/statement_modifier.rb', line 9

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 == 0
  return false if cond.each_node.any?(&:lvasgn_type?)
  return false if body_has_comment?(body)
  return false if end_keyword_has_comment?(node)

  indentation = node.loc.keyword.column
  kw_length = node.loc.keyword.size
  cond_length = cond.loc.expression.size
  space = 1
  total = indentation + body_length + space + kw_length + space +
          cond_length

  total <= max_line_length
end

#length(node) ⇒ Object


37
38
39
# File 'lib/rubocop/cop/mixin/statement_modifier.rb', line 37

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

#max_line_lengthObject


32
33
34
35
# File 'lib/rubocop/cop/mixin/statement_modifier.rb', line 32

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