class RuboCop::Cop::Style::RedundantInitialize
end
# Overriding to negate superclass ‘initialize` method.
def initialize
# bad
@example AllowComments: false
end
# Overriding to negate superclass `initialize` method.
def initialize
# good
@example AllowComments: true (default)
end
def initialize(…)
# good (changes the parameter requirements)
end
def initialize(**)
# good (changes the parameter requirements)
end
def initialize(*)
# good (changes the parameter requirements)
end
super
def initialize(a, b: 5)
# good (default value)
end
super
def initialize(a, b = 5)
# good (default value)
end
super(a)
def initialize(a, b)
# good (different number of parameters)
end
super
do_something
def initialize
# good
end
do_something
def initialize
# good
end
super(a, b)
def initialize(a, b)
# bad
end
super
def initialize(a, b)
# bad
end
super
def initialize
# bad
end
def initialize
# bad
@example
a different arity than superclass.
This cop is unsafe because if subclass overrides `initialize` method with
@safety
initializer.
to purposely create an empty `initialize` method to override a superclass’s
NOTE: Empty initializers are registered as offenses, but it is possible
to not be redundant.
NOTE: If an initializer argument has a default value, RuboCop assumes it
number of arguments as its superclass potentially does.
will not register an offense, because it allows the initializer to take a different
an argument that accepts multiple values (‘restarg`, `kwrestarg`, etc.) it
calls `super` with the same arguments given to it. If the initializer takes
An initializer is redundant if it does not do anything, or if it only
Checks for `initialize` methods that are redundant.
def acceptable?(node)
def acceptable?(node) !node.method?(:initialize) || forwards?(node) || allow_comments?(node) end
def allow_comments?(node)
def allow_comments?(node) return false unless cop_config['AllowComments'] contains_comments?(node) && !comments_contain_disables?(node, name) end
def forwards?(node)
def forwards?(node) node.arguments.each_child_node(:restarg, :kwrestarg, :forward_args, :forward_arg).any? end
def on_def(node)
def on_def(node) return if acceptable?(node) if node.body.nil? register_offense(node, MSG_EMPTY) else return if node.body.begin_type? if (args, super_node = initialize_forwards?(node)) return unless same_args?(super_node, args) register_offense(node, MSG) end end end
def register_offense(node, message)
def register_offense(node, message) add_offense(node, message: message) do |corrector| corrector.remove(range_by_whole_lines(node.source_range, include_final_newline: true)) end end
def same_args?(super_node, args)
def same_args?(super_node, args) return true if super_node.zsuper_type? args.map(&:name) == super_node.arguments.map { |a| a.children[0] } end