Ruby 在此方法调用方的上下文中调用super
我有几种方法,它们具有相似的条件逻辑,我认为干燥它们是合理的Ruby 在此方法调用方的上下文中调用super,ruby,Ruby,我有几种方法,它们具有相似的条件逻辑,我认为干燥它们是合理的 class A def parent1(val) puts "parent1 A #{val}" end def parent2(val) puts "parent2 A #{val}" end end class B < A def parent1(val) if val puts "foo" else super end end
class A
def parent1(val)
puts "parent1 A #{val}"
end
def parent2(val)
puts "parent2 A #{val}"
end
end
class B < A
def parent1(val)
if val
puts "foo"
else
super
end
end
def parent2(val)
if val
puts "bar"
else
super
end
end
end
编辑:这很有效,但看起来很疯狂
def puts_or_super(val, text)
if val
puts text
else
self.class.superclass.instance_method(caller[0][/`.*'/][1..-2].to_sym).bind(self).call
end
end
有更好的解决方案吗?假设您的定义在类
A
中,并且相关的超级方法在类B
中定义,以便A
继承自B
我认为你应该走另一条路。使B
a模块,并将B
前置到a
。然后,具有“foo”
、“bar”
等的定义将不是超级方法,条件将在前置模块中
module B
def parent1(val)
return super if val
... # your original logic in super class
end
def parent2(val)
return super if val
... # your original logic in super class
end
end
class A
prepend B
def parent1(_); puts "foo" end
def parent2(_); puts "bar" end
end
super
用于类继承。您使用两种不同的方法。您能否扩展您的示例以显示您希望在哪些类中使用您的示例?你想叫什么?我只是想简单点。parent1
和parent2
都属于继承自另一个类的类。也许我提供了一个不好的示例,所以我决定不回答我的问题,而是简化示例。对不起,那不是我需要的。基本上,我想干燥parent1
和parent2
方法,特别是super
调用部分。
module B
def parent1(val)
return super if val
... # your original logic in super class
end
def parent2(val)
return super if val
... # your original logic in super class
end
end
class A
prepend B
def parent1(_); puts "foo" end
def parent2(_); puts "bar" end
end