Class: Rubocop::Cop::Style::IfUnlessModifier
- Inherits:
-
Cop
- Object
- Parser::Rewriter
- Cop
- Rubocop::Cop::Style::IfUnlessModifier
show all
- Includes:
- FavorModifier
- Defined in:
- lib/rubocop/cop/style/favor_modifier.rb
Overview
Checks for if and unless statements that would fit on one line
if written as a modifier if/unless.
Instance Attribute Summary
Attributes inherited from Cop
#autocorrect, #debug, #disabled_lines, #offences
Instance Method Summary
collapse
#body_has_comment?, #body_length, #check, #length
Methods inherited from Cop
#add_offence, #autocorrect_action, cop_name, cop_type, #do_autocorrect, #ignore_node, inherited, #initialize, lint?, #name, rails?, style?
Instance Method Details
#elsif?(node) ⇒ Boolean
87
88
89
|
# File 'lib/rubocop/cop/style/favor_modifier.rb', line 87
def elsif?(node)
node.loc.keyword.is?('elsif')
end
|
#error_message ⇒ Object
59
60
61
62
|
# File 'lib/rubocop/cop/style/favor_modifier.rb', line 59
def error_message
'Favor modifier if/unless usage when you have a single-line body. ' +
'Another good alternative is the usage of control flow &&/||.'
end
|
#if_else?(node) ⇒ Boolean
91
92
93
|
# File 'lib/rubocop/cop/style/favor_modifier.rb', line 91
def if_else?(node)
node.loc.respond_to?(:else) && node.loc.else
end
|
#inspect(source_buffer, source, tokens, ast, comments) ⇒ Object
64
65
66
67
68
69
70
71
72
73
74
75
76
77
|
# File 'lib/rubocop/cop/style/favor_modifier.rb', line 64
def inspect(source_buffer, source, tokens, ast, )
return unless ast
on_node(:if, ast) do |node|
return if ternary_op?(node)
return if modifier_if?(node)
return if elsif?(node)
return if if_else?(node)
if check(node, )
add_offence(:convention, node.loc.expression, error_message)
end
end
end
|
#modifier_if?(node) ⇒ Boolean
83
84
85
|
# File 'lib/rubocop/cop/style/favor_modifier.rb', line 83
def modifier_if?(node)
node.loc.end.nil?
end
|
#ternary_op?(node) ⇒ Boolean
79
80
81
|
# File 'lib/rubocop/cop/style/favor_modifier.rb', line 79
def ternary_op?(node)
node.loc.respond_to?(:question)
end
|