我想动态地为Ruby中的类指定父类。请考虑以下代码:
class Agent
def self.hook_up(calling_class, desired_parent_class)
# Do some magic here
end
end
class Parent
def bar
puts "bar"
end
end
class Child
def foo
puts "foo"
end
Agent.hook_up(self, Parent)
end
Child.new.barParent和Child类定义都没有指定父类,因此它们都是从对象继承的。我的第一个问题是:我需要在Agent.hook_up中做什么才能使Parent成为Child的超类(例如,Child对象可以继承'bar‘方法)。
我的第二个问题是:我是否需要将第一个参数传递给Agent.hook_up,还是hook_up方法可以以编程方式确定调用它的类?
发布于 2010-06-27 11:57:00
约书亚已经给出了一个很好的选择列表,但是要回答你的问题:在用ruby创建类之后,您不能更改类的超类。这根本不可能。
发布于 2010-06-27 10:56:59
也许你在找这个
Child = Class.new Parent do
def foo
"foo"
end
end
Child.ancestors # => [Child, Parent, Object, Kernel]
Child.new.bar # => "bar"
Child.new.foo # => "foo"由于父类是Class.new的一个参数,所以可以与其他类交换它。
我以前在编写某些测试时使用过这种技术。但我很难想出许多好的借口来做这样的事。
我怀疑你真正想要的是一个模块。
class Agent
def self.hook_up(calling_class, desired_parent_class)
calling_class.send :include , desired_parent_class
end
end
module Parent
def bar
"bar"
end
end
class Child
def foo
"foo"
end
Agent.hook_up(self, Parent)
end
Child.ancestors # => [Child, Parent, Object, Kernel]
Child.new.bar # => "bar"
Child.new.foo # => "foo"不过,当然,根本不需要代理
module Parent
def bar
"bar"
end
end
class Child
def foo
"foo"
end
include Parent
end
Child.ancestors # => [Child, Parent, Object, Kernel]
Child.new.bar # => "bar"
Child.new.foo # => "foo"发布于 2010-06-28 01:05:54
只有Ruby1.9:(1.8类似,但使用RCLASS(self)->super代替)
require 'inline'
class Class
inline do |builder|
builder.c %{
VALUE set_super(VALUE sup) {
RCLASS(self)->ptr->super = sup;
return sup;
}
}
builder.c %{
VALUE get_super() {
return RCLASS(self)->ptr->super;
}
}
end
J = Class.new
J.set_super(Class.new)https://stackoverflow.com/questions/3127069
复制相似问题