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.

Instance Attribute Summary

Attributes inherited from Cop

#autocorrect, #debug, #disabled_lines, #offences

Instance Method Summary collapse

Methods included from FavorModifier

#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?

Constructor Details

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

Instance Method Details

#elsif?(node) ⇒ Boolean

Returns:

  • (Boolean)


87
88
89
# File 'lib/rubocop/cop/style/favor_modifier.rb', line 87

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

#error_messageObject



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

Returns:

  • (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, comments)
  return unless ast
  on_node(:if, ast) do |node|
    # discard ternary ops, if/else and modifier if/unless nodes
    return if ternary_op?(node)
    return if modifier_if?(node)
    return if elsif?(node)
    return if if_else?(node)

    if check(node, comments)
      add_offence(:convention, node.loc.expression, error_message)
    end
  end
end

#modifier_if?(node) ⇒ Boolean

Returns:

  • (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

Returns:

  • (Boolean)


79
80
81
# File 'lib/rubocop/cop/style/favor_modifier.rb', line 79

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