簡體   English   中英

Ruby inheritance,方法未傳遞給子 class

[英]Ruby inheritance, method not being passed to a child class

我有一個 ruby 練習,並且不能完全超過一分。 當我運行測試時,它會undefined method "attribute" for CommentSerializer:Class 雖然,在serializer.rb中定義了這樣一個方法,它是從中繼承的。

我在這里缺少關於 ruby 中的 inheritance 的內容嗎?

注意:我不允許添加除下面列出的兩個之外的任何 gem,也不允許修改除serializer.rb之外的任何文件。

以下是文件:

寶石文件:

gem 'rspec'
gem 'pry'

應用程序/comment.rb:

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

應用程序/comment_serializer.rb:

require_relative "serializer"

class CommentSerializer < Serializer
  attribute :id
  attribute :body
end

應用程序/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

規范/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定義的主體中調用類似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。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM