我有以下 Ruby 类:
class Sandwich
class << self
def prepare_with(special_ingredient, &block)
# Some very very special magic is done here to
# call instead just .fry! as .fry!({:ingredient=>special_ingredient})
# and for any other method the same
end
def fry!(opts= {})
end
def add_mayo(opts = {})
end
end
end
class Hamburger < Sandwich
end
=> Hamburger.prepare_with(bacon) do
=> Hamburger.fry!
=> Hamburger.add_mayo
=> end
我想修改调用Hamburger
类的所有方法并将附加添加key=>value
到最后一个参数哈希中。
应该使用一些特殊的魔法来Sandwich.prepare_with
调用 Sandwich 的所有方法(及其所有后代),例如as 。call
.fry!
.fry!({:ingredient=>special_ingredient})
已编辑:理想情况下,我们需要过滤内部块代码的调用的附加点,例如以下代码会引发任何 prepare_with 代码的异常,它不会过滤它使用附加参数调用的方法:
=> Hamburger.prepare_with(bacon) do
=> Hamburger.fry!
=> h = Hash.new("Go fish")
=> Hamburger.add_mayo
=> end