Class: Rubocop::Cop::IfThenElse
- Defined in:
- lib/rubocop/cop/if_then_else.rb
Constant Summary collapse
- ERROR_MESSAGE =
{ multiline_if_then: 'Never use then for multi-line if/unless.', one_liner: 'Favor the ternary operator (?:) over if/then/else/end constructs.', semicolon: 'Never use if x; Use the ternary operator instead.' }
Instance Attribute Summary
Attributes inherited from Cop
Instance Method Summary collapse
Methods inherited from Cop
#add_offence, enabled?, #has_report?, inherited, #initialize
Constructor Details
This class inherits a constructor from Rubocop::Cop::Cop
Instance Method Details
#inspect(file, source, tokens, sexp) ⇒ Object
15 16 17 18 19 20 21 22 |
# File 'lib/rubocop/cop/if_then_else.rb', line 15 def inspect(file, source, tokens, sexp) tokens.each_with_index do |t, ix| if t.type == :on_kw && ['if', 'unless'].include?(t.text) error = ERROR_MESSAGE[kind_of_if(tokens, ix + 1)] add_offence(:convention, t.pos.lineno, error) if error end end end |
#kind_of_if(tokens, ix) ⇒ Object
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
# File 'lib/rubocop/cop/if_then_else.rb', line 24 def kind_of_if(tokens, ix) then_found = false tokens[ix..-1].each do |t| case t.type when :on_kw case t.text when 'then' then then_found = true when 'end' then return :one_liner end when :on_ignored_nl, :on_nl break when :on_semicolon return :semicolon when :on_comment break if t.text =~ /\n/ when :on_sp nil else then_found = false end end then_found ? :multiline_if_then : nil end |