从 Ruby 中继承的 Class 调用方法

Calling Methods from Inherited Class in Ruby

我有以下 classes:

模块

module AlertService
    module MessageTemplate
      def generate_message
        "test"
      end
    end
  end

Parent class:

module Client
  def post uri, params={}
    Net::HTTP.post_form uri, params
  end
end

module AlertService
  class BaseAlert
    extend MessageTemplate
    include Singleton
    include Client
    def initialize; end
  end
end

Child Class:

module AlertService
class TestAlert < BaseAlert
  include Singleton
  def initialize
  options = {
    username: "Screen Alert Bot",
    http_client: Client
  }
  @notifier = Slack::Notifier.new(rails.config.url, options)
  end

  def self.create_message
    message = generate_message
  end

  def self.send_message
    create_message
    @notifier.post blocks: message
  end
end
end

我可以这样创建测试警报:s= AlertService::TestAlert

但是当我这样做时出现错误:

s.send_message

NoMethodError: undefined method `generate_message' for AlertService::TestAlert::Class

generate_message 是 BaseAlert class 中包含的 MessageTemplate 模块中的一个方法。为什么说我继承的 class 无法访问该方法?

您没有正确使用 Singleton。您包含它,但随后不使用它,而是完全绕过它并调用与 Singleton 无关的 class 方法。他们依次调用父 class 上不存在的 class 方法。

解决方案是按预期使用 Singleton

module AlertService
  class BaseAlert
    include MessageTemplate
    include Singleton

    def initialize
    end
  end
end

module AlertService
  class TestAlert < BaseAlert
    def initialize
      @notifier = Slack::Notifier.new(Rails.configuration.url, Rails.configuration.options)
    end

    def create_message
      message = generate_message
    end

    def send_message
      create_message
      @notifier.post blocks: message
    end
  end
end

你现在在哪里 call with instance as documented:

AlertService::TestAlert.instance.send_message