【发布时间】:2010-08-05 13:41:22
【问题描述】:
我有 2 个类,它们的对象应该充当“合作伙伴”。第一个是我的Thing 类,它的实例应该充当宝石RubyTree 的Tree::TreeNodes。
基本上,这个委托可以使用Forwardable来实现:
class Thing < NoClassInheritancePlease
extend Forwardable
def initialize(title = "node")
@node = Tree::TreeNode.new title
# Collect node methods that should be delegated
node_methods = @node.public_methods(false)
node_methods += @node.protected_methods
node_methods -= (public_methods(false) + protected_methods(false) + private_methods) # own methods should not been delegated
# Set up delegation of specified node methods as singleton methods
for method in node_methods
Base.def_delegator :@node, method
end
end
end
问题:
许多TreeNode 方法参考self。例如:
def each(&block) # :yields: node
yield self
children { |child| child.each(&block) }
end
因此,my_thing.each {...} 产生self,即属于my_thing 的Tree::TreeNode 对象,但不属于Thing 对象本身。
另一个例子:
siblings = []
parent.children {|my_sibling| siblings << my_sibling if my_sibling != self}
siblings
parent.children 返回一个 Things 数组,因此条件永远不会评估为 false,因为 my_sibling 是 Thing(这很好)但 self 是 Tree::TreeNode
问题:如何在另一个类(例如Thing)的上下文中评估一个类(例如Tree::TreeNode)的实例方法? (“覆盖自我”)
我尝试使用 UnboundMethods,但您只能将原始接收类的实例绑定到未绑定方法。
【问题讨论】:
-
你确定没有别的办法吗?你的方法似乎……有缺陷。
-
好吧,除了复制和粘贴或不使用这些方法之外别无他法。我想我有一天会分叉 RubyTree 以使其可委托。
标签: ruby reflection delegates metaprogramming