从Ruby中的父类调用派生类实例方法

时间:2018-07-12 13:03:46

标签: ruby-on-rails ruby

我有一个父类Parent及其子类ChildChild类包含一个方法child_method,我必须从Parent类中调用该方法。我尝试了几种方法,其中一种方法如下:

class Child < Parent
  def child_method(params)
    # ...
  end

  def some_other_method(params)
    Parent.call_child_method(params, &method(:child_method))
  end
end

class Parent
  def self.call_child_method(params, &callback)
    # Some common code which it's Child classes share
    callback.call(params)
  end
end

以下是我得到的错误:

NameError Exception: undefined local variable or method `params' 
for <Child:0x00000000154f53e8>
Did you mean?  params

以防万一,您想知道为什么我不直接从child_method类本身调用Child。好吧,这是因为两个不同的子类复制了该代码,然后又用不同的参数和约束调用了不同的方法的原因,使得我无法从call_child_method类调用Child然后返回致电child_method。当我仅在“ call_child_method”内部时,我必须调用这些方法(其他子类具有另一个具有不同数量参数的方法)。而且,旧代码不是我写的,由于时间限制,我不想重构整个设计逻辑。那么,我在这里有什么选择?

2 个答案:

答案 0 :(得分:1)

您的代码几乎可以运行,但是在定义def方法时您忘记了call_child_method关键字。

以下内容适用于我的系统:

class Parent                                                                    
  def self.call_child_method(params, &callback)                                 
  # Some common code which it's Child classes share                             
    callback.call(params)                                                       
  end                                                                           
end                                                                             

class Child < Parent                                                            
  def child_method(params)                                                   
    p "The params are", params                                               
  end                                                                        

  def some_other_method(params)                                              
    Parent.call_child_method(params, &method(:child_method))                 
  end                                                                        
end                                                                             

Child.new.some_other_method("hello")

我得到输出:

"The params are"
"hello"

答案 1 :(得分:1)

您的代码已经可以使用,所以我不知道问题是什么。

但是,我要说的是,有一种标准的方式可以处理这样的控制流,而无需借助method元编程: yield 。您可以执行以下操作:

class Parent
  def common_logic(params)
    # Some common code which it's Child classes share
    yield
  end
end

class Child < Parent
  def child_method(params)
    # ...
  end

  def some_other_method(params)
    common_logic(params) { child_method(params) }
  end
end