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



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

def body_length(body)
  if body
    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
# 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

  if %w(if while).include?(sexp.loc.keyword.source)
    cond, body = *sexp
  else
    cond, _else, 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)

    (cond_length + body_length) <= LineLength.max
  end
end

#length(sexp) ⇒ Object



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

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