Class: RuboCop::Cop::Operandi::RedundantOptional

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector
Defined in:
lib/operandi/rubocop/cop/operandi/redundant_optional.rb

Overview

Detects when optional: true is used together with default: option. Having a default value implies the argument/output is optional, making optional: true redundant.

Examples:

# bad
arg :name, type: String, optional: true, default: "guest"
output :count, type: Integer, optional: true, default: 0

# good
arg :name, type: String, default: "guest"
output :count, type: Integer, default: 0

Constant Summary collapse

MSG =
"`optional: true` is redundant when `default:` is specified for `%<name>s`."
RESTRICT_ON_SEND =
[:arg, :output].freeze

Instance Method Summary collapse

Instance Method Details

#field_call?(node) ⇒ Object



30
31
32
# File 'lib/operandi/rubocop/cop/operandi/redundant_optional.rb', line 30

def_node_matcher :field_call?, <<~PATTERN
  (send nil? {:arg :output} (sym $_) ...)
PATTERN

#on_send(node) ⇒ Object



34
35
36
37
38
39
40
41
42
43
# File 'lib/operandi/rubocop/cop/operandi/redundant_optional.rb', line 34

def on_send(node)
  field_call?(node) do |name|
    optional_pair = find_optional_true_pair(node)
    return unless optional_pair && has_default_option?(node)

    add_offense(node, message: format(MSG, name: name)) do |corrector|
      remove_hash_pair(corrector, node.arguments[1], optional_pair)
    end
  end
end