Class: Rubocop::Cop::Style::IfUnlessModifier

Inherits:
Cop
  • Object
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.

Constant Summary

Constants inherited from Cop

Cop::OPERATOR_METHODS

Instance Attribute Summary

Attributes inherited from Cop

#config, #corrections, #offences, #processed_source

Instance Method Summary collapse

Methods included from FavorModifier

#body_has_comment?, #body_length, #check, #conditional_length, #length, #max_line_length

Methods inherited from Cop

#add_offence, all, #autocorrect?, #convention, #cop_config, cop_name, #cop_name, cop_type, #debug?, #ignore_node, inherited, #initialize, lint?, #message, non_rails, rails?, style?, #support_autocorrect?, #warning

Constructor Details

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

Instance Method Details

#elsif?(node) ⇒ Boolean

Returns:

  • (Boolean)


101
102
103
# File 'lib/rubocop/cop/style/favor_modifier.rb', line 101

def elsif?(node)
  node.loc.keyword.is?('elsif')
end

#error_messageObject



73
74
75
76
# File 'lib/rubocop/cop/style/favor_modifier.rb', line 73

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

Returns:

  • (Boolean)


105
106
107
# File 'lib/rubocop/cop/style/favor_modifier.rb', line 105

def if_else?(node)
  node.loc.respond_to?(:else) && node.loc.else
end

#investigate(processed_source) ⇒ Object



78
79
80
81
82
83
84
85
86
87
88
89
90
91
# File 'lib/rubocop/cop/style/favor_modifier.rb', line 78

def investigate(processed_source)
  return unless processed_source.ast
  on_node(:if, processed_source.ast) do |node|
    # discard ternary ops, if/else and modifier if/unless nodes
    next if ternary_op?(node)
    next if modifier_if?(node)
    next if elsif?(node)
    next if if_else?(node)

    if check(node, processed_source.comments)
      convention(node, :keyword, error_message)
    end
  end
end

#modifier_if?(node) ⇒ Boolean

Returns:

  • (Boolean)


97
98
99
# File 'lib/rubocop/cop/style/favor_modifier.rb', line 97

def modifier_if?(node)
  node.loc.end.nil?
end

#ternary_op?(node) ⇒ Boolean

Returns:

  • (Boolean)


93
94
95
# File 'lib/rubocop/cop/style/favor_modifier.rb', line 93

def ternary_op?(node)
  node.loc.respond_to?(:question)
end