Module: Rubocop::Cop::FavorModifier

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

Instance Method Summary collapse

Instance Method Details

#body_length(body) ⇒ Object



30
31
32
33
34
35
36
# File 'lib/rubocop/cop/favor_modifier.rb', line 30

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

#check(sexp) ⇒ Object

TODO extremely ugly solution that needs lots of polish



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/rubocop/cop/favor_modifier.rb', line 7

def check(sexp)
  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
    indentation = sexp.loc.keyword.column
    cond_length = sexp.loc.keyword.size + cond.loc.expression.size + 1
    body_length = body_length(body)

    body_length > 0 &&
      (indentation + cond_length + body_length) <= LineLength.max
  end
end

#length(sexp) ⇒ Object



26
27
28
# File 'lib/rubocop/cop/favor_modifier.rb', line 26

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