diff --git a/CHANGELOG.md b/CHANGELOG.md index 6d8dc4627eb..79808a63e09 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,6 +19,7 @@ ### Changes * [#8470](https://github.com/rubocop-hq/rubocop/issues/8470): Do not autocorrect `Style/StringConcatenation` when parts of the expression are too complex. ([@dvandersluis][]) +* [#8561](https://github.com/rubocop-hq/rubocop/issues/8561): Fix `Lint/UselessMethodDefinition` to not register an offense when method definition includes optional arguments. ([@fatkodima][]) * [#8617](https://github.com/rubocop-hq/rubocop/issues/8617): Fix `Style/HashAsLastArrayItem` to not register an offense when all items in an array are hashes. ([@dvandersluis][]) ## 0.90.0 (2020-09-01) diff --git a/docs/modules/ROOT/pages/cops_lint.adoc b/docs/modules/ROOT/pages/cops_lint.adoc index a842e8d9aaf..c1ac48c9589 100644 --- a/docs/modules/ROOT/pages/cops_lint.adoc +++ b/docs/modules/ROOT/pages/cops_lint.adoc @@ -4621,6 +4621,11 @@ def method super end +# good - with default arguments +def initialize(x = Object.new) + super +end + # good def initialize initialize_internals diff --git a/lib/rubocop/cop/lint/useless_method_definition.rb b/lib/rubocop/cop/lint/useless_method_definition.rb index e38b06e7532..c86e43f6059 100644 --- a/lib/rubocop/cop/lint/useless_method_definition.rb +++ b/lib/rubocop/cop/lint/useless_method_definition.rb @@ -18,6 +18,11 @@ module Lint # super # end # + # # good - with default arguments + # def initialize(x = Object.new) + # super + # end + # # # good # def initialize # initialize_internals @@ -46,6 +51,7 @@ class UselessMethodDefinition < Base MSG = 'Useless method definition detected.' def on_def(node) + return if optional_args?(node) return unless (constructor?(node) && empty_constructor?(node)) || delegating?(node.body, node) @@ -55,6 +61,10 @@ def on_def(node) private + def optional_args?(node) + node.arguments.any? { |arg| arg.optarg_type? || arg.kwoptarg_type? } + end + def empty_constructor?(node) return false if node.body return false if cop_config['AllowComments'] && comment_lines?(node) diff --git a/spec/rubocop/cop/lint/useless_method_definition_spec.rb b/spec/rubocop/cop/lint/useless_method_definition_spec.rb index 77dfd4c90da..c8cde11b7b6 100644 --- a/spec/rubocop/cop/lint/useless_method_definition_spec.rb +++ b/spec/rubocop/cop/lint/useless_method_definition_spec.rb @@ -148,6 +148,22 @@ def method2(foo, bar) RUBY end + it 'does not register an offense when method definition contains optional argument' do + expect_no_offenses(<<~RUBY) + def method(x = 1) + super + end + RUBY + end + + it 'does not register an offense when method definition contains optional keyword argument' do + expect_no_offenses(<<~RUBY) + def method(x: 1) + super + end + RUBY + end + it 'does not register an offense when non-constructor contains only comments' do expect_no_offenses(<<~RUBY) def non_constructor