【问题标题】:Can a parent class have a parent method that appends extra functionality?父类可以有一个附加额外功能的父方法吗?
【发布时间】:2013-07-13 23:34:59
【问题描述】:

我有一个名为Question 的父类。问题有很多种。

其中一个是MultipleChoice。所有像MultipleChoice 这样的子问题类都有一个名为generate_response 的方法,它返回一个json 对象,其中包含我的应用程序的其余部分产生问题所需的所有部分。

为了使我的应用程序更干燥,我注意到这个返回的 JSON 对象中的一些项目是类似的调用。例如,:title 始终是子类的title

有没有办法我可以在Question 中编写一个父方法,将这个静态信息附加到来自generate_response 的 JSON 返回中

例子:

class MultipleChoice < Question
  def generate_response
    {
      title: title
      explanation: explanation
      first_time: check_if_first
    }
  end

class Question < ActiveRecord::Base
 # is there a way inside of this class to append my static info to any child class usage of the method `generate_response`?

【问题讨论】:

  • 与语言无关的标签在这里有什么作用?
  • 方法中与super 的一般关系。我想大多数编程语言都有这个问题。

标签: ruby-on-rails ruby methods language-agnostic


【解决方案1】:

你可以使用super

class Question < ActiveRecord::Base
  def generate_response(obj)
    static info
  end
end

class InheritsFromQuestion < Question
  def generate_response
    super(self) #this will call the parent class (Question) method
    rest of whatever
  end
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-10-07
    • 1970-01-01
    • 1970-01-01
    • 2021-08-08
    • 1970-01-01
    • 2021-10-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多