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



33
34
35
36
37
38
39
# File 'lib/rubocop/cop/favor_modifier.rb', line 33

def body_length(body)
  if body && body.loc.expression
    body.loc.expression.column + 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
25
26
27
# File 'lib/rubocop/cop/favor_modifier.rb', line 7

def check(sexp)
  # discard if/then/else
  return false if sexp.loc.respond_to?(:else) && sexp.loc.else
  # discard modifier while/until
  return false if [:while, :until].include?(sexp.type) && !sexp.loc.end

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

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

#length(sexp) ⇒ Object



29
30
31
# File 'lib/rubocop/cop/favor_modifier.rb', line 29

def length(sexp)
  sexp.loc.expression.source.split("\n").size
end