Class: Rubocop::Cop::Style::MultilineIfThen

Inherits:
Cop
  • Object
show all
Includes:
IfThenElse
Defined in:
lib/rubocop/cop/style/multiline_if_then.rb

Overview

Checks for uses of the then keyword in multi-line if statements.

Examples:

This is considered bad practice:


if cond then
end

If statements can contain then on the same line:


if cond then a
elsif cond then b
end

Constant Summary

Constants inherited from Cop

Cop::OPERATOR_METHODS

Constants included from Util

Util::PROC_NEW_NODE

Instance Attribute Summary

Attributes inherited from Cop

#config, #corrections, #offences, #processed_source

Instance Method Summary collapse

Methods included from IfThenElse

#check, #on_if, #on_unless

Methods inherited from Cop

#add_offence, all, #autocorrect?, #config_to_allow_offences, #config_to_allow_offences=, #cop_config, cop_name, #cop_name, cop_type, #debug?, #exclude_file?, #exclude_paths, #ignore_node, #include_file?, #include_paths, inherited, #initialize, lint?, #message, non_rails, rails?, #relevant_file?, style?, #support_autocorrect?

Methods included from Util

block_length, command?, comment_line?, const_name, first_part_of_call_chain, lambda?, lambda_or_proc?, line_range, on_node, proc?, range_with_surrounding_space, source_range, strip_quotes

Constructor Details

This class inherits a constructor from Rubocop::Cop::Cop

Instance Method Details

#end_position(conditional_node) ⇒ Object



39
40
41
42
43
44
45
46
47
# File 'lib/rubocop/cop/style/multiline_if_then.rb', line 39

def end_position(conditional_node)
  node = if conditional_node.type == :match_current_line
           conditional_node.children.first
         else
           conditional_node
         end

  node.loc.expression.end.end_pos
end

#error_messageObject



49
50
51
# File 'lib/rubocop/cop/style/multiline_if_then.rb', line 49

def error_message
  'Never use then for multi-line if/unless.'
end

#offending_line(node) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/rubocop/cop/style/multiline_if_then.rb', line 21

def offending_line(node)
  condition, body, else_clause = *node
  next_thing = if body && body.loc.expression
                 body.loc.expression.begin
               elsif else_clause && else_clause.loc.expression
                 else_clause.loc.expression.begin
               else
                 node.loc.end # No body, use "end".
               end
  right_after_cond =
    Parser::Source::Range.new(next_thing.source_buffer,
                              end_position(condition),
                              next_thing.begin_pos)
  if right_after_cond.source =~ /\A\s*then\s*(#.*)?\s*\n/
    node.loc.expression.begin.line
  end
end