简体   繁体   English

Ruby inheritance,方法未传递给子 class

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

I've got a ruby exercise, and cannot quite get past one point.我有一个 ruby 练习,并且不能完全超过一分。 When I run the tests, it throws undefined method "attribute" for CommentSerializer:Class .当我运行测试时,它会undefined method "attribute" for CommentSerializer:Class Though, there is such a method defined in serializer.rb , from which it's being inherited.虽然,在serializer.rb中定义了这样一个方法,它是从中继承的。

Am I missing something about inheritance in ruby here?我在这里缺少关于 ruby 中的 inheritance 的内容吗?

Note : I am neither allowed to add any gems other than the two listed below, nor to modify any file other than serializer.rb .注意:我不允许添加除下面列出的两个之外的任何 gem,也不允许修改除serializer.rb之外的任何文件。

Here are the files:以下是文件:

Gemfile:宝石文件:

gem 'rspec'
gem 'pry'

app/comment.rb:应用程序/comment.rb:

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

app/comment_serializer.rb:应用程序/comment_serializer.rb:

require_relative "serializer"

class CommentSerializer < Serializer
  attribute :id
  attribute :body
end

app/serializer.rb:应用程序/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:规范/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

If you call something like attribute in the body of the class definition then it happens in the class context at that exact moment , as in:如果您在class定义的主体中调用类似attribute的内容,那么它会在该确切时刻发生在 class 上下文中,如:

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

There must be a corresponding class method to receive that call, as in:必须有相应的class 方法才能接收该调用,如下所示:

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

Since you're inheriting that method it will be defined prior to calling it, but that's not the case if you have something like:由于您要继承该方法,因此将在调用它之前对其进行定义,但如果您有类似的情况,情况并非如此:

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

  def self.attribute(name)
  end
end

The method is defined after it's called, so you get this error.该方法是在调用后定义的,因此您会收到此错误。 You must either reverse the order, define first, call second, or put it into a parent class.您必须颠倒顺序,首先定义,然后调用,或者将其放入父 class。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM