Module: RuboCop::Cop::StatementModifier
Overview
Common functionality for modifier cops.
Instance Method Summary
collapse
Methods included from IfNode
#elsif?, #if_else?, #if_node_parts, #modifier_if?, #ternary?
#def_node_matcher, #def_node_search, #node_search, #node_search_all, #node_search_body, #node_search_first
Instance Method Details
#body_length(body) ⇒ Object
61
62
63
|
# File 'lib/rubocop/cop/mixin/statement_modifier.rb', line 61
def body_length(body)
body.source_range ? body.source_range.size : 0
end
|
69
70
71
|
# File 'lib/rubocop/cop/mixin/statement_modifier.rb', line 69
def
@comment_lines ||= processed_source..map { |c| c.location.line }
end
|
65
66
67
|
# File 'lib/rubocop/cop/mixin/statement_modifier.rb', line 65
def (source)
.include?(source.line)
end
|
#empty_body?(body) ⇒ Boolean
57
58
59
|
# File 'lib/rubocop/cop/mixin/statement_modifier.rb', line 57
def empty_body?(body)
body_length(body).zero?
end
|
40
41
42
43
44
45
46
|
# File 'lib/rubocop/cop/mixin/statement_modifier.rb', line 40
def length_in_modifier_form(node, cond, body_length)
indentation = node.loc.keyword.column
kw_length = node.loc.keyword.size
cond_length = cond.source_range.size
space = 1
indentation + body_length + space + kw_length + space + cond_length
end
|
#line_count(node) ⇒ Object
53
54
55
|
# File 'lib/rubocop/cop/mixin/statement_modifier.rb', line 53
def line_count(node)
node.source.lines.grep(/\S/).size
end
|
#max_line_length ⇒ Object
48
49
50
51
|
# File 'lib/rubocop/cop/mixin/statement_modifier.rb', line 48
def max_line_length
cop_config['MaxLineLength'] ||
config.for_cop('Metrics/LineLength')['Max']
end
|
#modifier_fits_on_single_line?(node) ⇒ Boolean
33
34
35
36
37
38
|
# File 'lib/rubocop/cop/mixin/statement_modifier.rb', line 33
def modifier_fits_on_single_line?(node)
cond, body, = if_node_parts(node)
body_length = body_length(body)
length_in_modifier_form(node, cond, body_length) <= max_line_length
end
|
#non_eligible_body?(body) ⇒ Boolean
23
24
25
26
27
|
# File 'lib/rubocop/cop/mixin/statement_modifier.rb', line 23
def non_eligible_body?(body)
return true unless body
body.begin_type? || empty_body?(body) || (body.source_range)
end
|
#non_eligible_condition?(condition) ⇒ Boolean
29
30
31
|
# File 'lib/rubocop/cop/mixin/statement_modifier.rb', line 29
def non_eligible_condition?(condition)
condition.each_node.any?(&:lvasgn_type?)
end
|
#non_eligible_node?(node) ⇒ Boolean
19
20
21
|
# File 'lib/rubocop/cop/mixin/statement_modifier.rb', line 19
def non_eligible_node?(node)
line_count(node) > 3 || (node.loc.end)
end
|
#single_line_as_modifier?(node) ⇒ Boolean
10
11
12
13
14
15
16
17
|
# File 'lib/rubocop/cop/mixin/statement_modifier.rb', line 10
def single_line_as_modifier?(node)
cond, body, = if_node_parts(node)
return false if non_eligible_node?(node) || non_eligible_body?(body) ||
non_eligible_condition?(cond)
modifier_fits_on_single_line?(node)
end
|