Module: Rubocop::Cop::Style::FavorModifier

Includes:
IfNode
Included in:
IfUnlessModifier, WhileUntilModifier
Defined in:
lib/rubocop/cop/style/favor_modifier.rb

Overview

Common functionality for modifier cops.

Instance Method Summary collapse

Methods included from IfNode

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

Instance Method Details

#body_has_comment?(body, comments) ⇒ Boolean

Returns:

  • (Boolean)


63
64
65
66
67
# File 'lib/rubocop/cop/style/favor_modifier.rb', line 63

def body_has_comment?(body, comments)
  comment_lines = comments.map(&:location).map(&:line)
  body_line = body.loc.expression.line
  comment_lines.include?(body_line)
end

#body_length(body) ⇒ Object



55
56
57
58
59
60
61
# File 'lib/rubocop/cop/style/favor_modifier.rb', line 55

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

#check(sexp, comments) ⇒ Object

TODO: Extremely ugly solution that needs lots of polish.



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/rubocop/cop/style/favor_modifier.rb', line 11

def check(sexp, comments)
  case sexp.loc.keyword.source
  when 'if'     then cond, body, _else = *sexp
  when 'unless' then cond, _else, body = *sexp
  else               cond, body = *sexp
  end

  return false if length(sexp) > 3

  body_length = body_length(body)

  return false if body_length == 0

  on_node(:lvasgn, cond) do
    return false
  end

  indentation = sexp.loc.keyword.column
  kw_length = sexp.loc.keyword.size
  cond_length = conditional_length(cond)
  space = 1
  total = indentation + body_length + space + kw_length + space +
    cond_length
  total <= max_line_length && !body_has_comment?(body, comments)
end

#conditional_length(conditional_node) ⇒ Object



45
46
47
48
49
50
51
52
53
# File 'lib/rubocop/cop/style/favor_modifier.rb', line 45

def conditional_length(conditional_node)
  node = if conditional_node.type == :match_current_line
           conditional_node.children.first
         else
           conditional_node
         end

  node.loc.expression.size
end

#length(sexp) ⇒ Object



41
42
43
# File 'lib/rubocop/cop/style/favor_modifier.rb', line 41

def length(sexp)
  sexp.loc.expression.source.lines.to_a.size
end

#max_line_lengthObject



37
38
39
# File 'lib/rubocop/cop/style/favor_modifier.rb', line 37

def max_line_length
  config.for_cop('LineLength')['Max']
end