Rubocop:即使超类没有初始化,也可以调用 super 来初始化父类的状态

use*_*887 4 ruby ruby-on-rails rubocop

Rubocop 突然抱怨没有调用 super 的类。

W: Lint/MissingSuper: Call `super` to initialize state of the parent class.
Run Code Online (Sandbox Code Playgroud)

例子:

# frozen_string_literal: true

class ApplicationService
  class << self
    def call(*args)
      new(*args).call
    end
  end

  def initialize(_args)
    raise NotImplementedError
  end

  def call
    raise NotImplementedError
  end
end
Run Code Online (Sandbox Code Playgroud)
class SampleService < ApplicationService
  def initialize(something)
    @something = something
  end

  def call
   # do something
  end

  private

  # remaining methods
end
Run Code Online (Sandbox Code Playgroud)

我有ApplicationService一种轻松调用服务的方法SampleService.call(arguments)

小智 12

对于您可以在 .rubocop.yml 中设置的服务:

Lint/MissingSuper:
  Exclude:
    - 'app/services/**/*'
Run Code Online (Sandbox Code Playgroud)

来源:建议在初始化时调用 super

  • 有趣的是,这个示例几乎相同:https://github.com/rubocop-hq/ruby-style-guide/issues/809#issuecomment-673096138 (3认同)