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

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

Overview

Common functionality for modifier cops.

Instance Method Summary collapse

Instance Method Details

#body_has_comment?(body, comments) ⇒ Boolean

Returns:

  • (Boolean)


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

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



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

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.



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

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

  if length(sexp) > 3
    false
  else
    body_length = body_length(body)

    if body_length == 0
      false
    else
      indentation = sexp.loc.keyword.column
      kw_length = sexp.loc.keyword.size
      cond_length = cond.loc.expression.size
      space = 1
      total = indentation + body_length + space + kw_length + space +
        cond_length
      total <= LineLength.max && !body_has_comment?(body, comments)
    end
  end
end

#length(sexp) ⇒ Object



35
36
37
# File 'lib/rubocop/cop/style/favor_modifier.rb', line 35

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