Ruby 继承,未传递给子方法的方法 class

Ruby inheritance, method not being passed to a child class

我有一个 ruby 练习,不能完全超过一点。 当我 运行 测试时,它抛出 undefined method "attribute" for CommentSerializer:Class。 虽然,在 serializer.rb 中定义了这样一个方法,它是从中继承的。

我在这里 ruby 中是否遗漏了有关继承的内容?

注意:除了下面列出的两个之外,我不允许添加任何gem,也不允许修改serializer.rb.

以外的任何文件

文件如下:

宝石文件:

gem 'rspec'
gem 'pry'

app/comment.rb:

Comment = Struct.new(:id, :body)

app/comment_serializer.rb:

require_relative "serializer"

class CommentSerializer < Serializer
  attribute :id
  attribute :body
end

app/serializer.rb:

class Serializer
  def initialize(object)
    @obj = object
  end

  def serialize
    obj.members.inject({}) do |hash, member|
      hash[member] = obj[member]
      hash
    end
  end

  def attribute(key)
  end

  private

  def obj
    @obj
  end
end

spec/comment_serializer_spec.rb:

require "date"
require_relative "spec_helper"
require_relative "../app/comment"
require_relative "../app/comment_serializer"

RSpec.describe CommentSerializer do
  subject { described_class.new(comment) }

  let(:comment) do
    Comment.new(1, "Foo bar")
  end

  it "serializes object" do
    expect(subject.serialize).to eq({
      id: 1,
      body: "Foo bar",
    })
  end
end

如果您在 class 定义的 body 中调用类似 attribute 的内容,那么它会在 class 上下文中发生 在那一刻,如:

class Example < Serializer
  # This is evaluated immediately, as in self.attribute(:a) or Example.attribute(:a)
  attribute :a
end

必须有相应的class方法来接收那个调用,如:

class Serializer
  def self.attribute(name)
    # ...
  end
end

由于您继承了该方法,因此将在调用它之前对其进行定义,但如果您有类似的东西,则情况并非如此:

class Example
  attribute :a # undefined method `attribute' for Example:Class (NoMethodError)

  def self.attribute(name)
  end
end

方法是在调用之后定义的,所以你会得到这个错误。您必须颠倒顺序,首先定义,然后调用,或者将其放入父项 class.