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

Inherits:
Cop
  • Object
show all
Includes:
IfNode, 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 included from Util

Util::ASGN_NODES, Util::EQUALS_ASGN_NODES, Util::OPERATOR_METHODS, Util::PROC_NEW_NODE, Util::SHORTHAND_ASGN_NODES

Instance Attribute Summary

Attributes inherited from Cop

#config, #corrections, #offenses, #processed_source

Instance Method Summary collapse

Methods included from IfThenElse

#check, #on_if, #on_unless

Methods included from IfNode

#elsif?, #if_else?, #modifier_if?, #ternary_op?

Methods inherited from Cop

#add_offense, all, #autocorrect?, #config_to_allow_offenses, #config_to_allow_offenses=, #cop_config, cop_name, #cop_name, cop_type, #debug?, #display_cop_names?, #exclude_file?, #include_file?, inherited, #initialize, lint?, #message, non_rails, rails?, #relevant_file?, #support_autocorrect?

Methods included from IgnoredNode

#ignore_node, #ignored_node?, #part_of_ignored_node?

Methods included from Util

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

Methods included from PathUtil

match_path?, relative_path

Constructor Details

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

Instance Method Details

#end_position(conditional_node) ⇒ Object



40
41
42
# File 'lib/rubocop/cop/style/multiline_if_then.rb', line 40

def end_position(conditional_node)
  conditional_node.loc.expression.end.end_pos
end

#error_message(node) ⇒ Object



44
45
46
# File 'lib/rubocop/cop/style/multiline_if_then.rb', line 44

def error_message(node)
  "Never use `then` for multi-line `#{node.loc.keyword.source}`."
end

#offending_line(node) ⇒ Object



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

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