有时你可以将 Ruby 倒入浓缩咖啡杯中。让我们看看如何。
这是一个模块 FunNotFun...
module FunNotFun
def fun
@method_type = 'fun'
end
def notfun
@method_type = 'not fun'
end
def method_added(id)
return unless @method_type
return if @bypass_method_added_hook
orig_method = instance_method(id)
@bypass_method_added_hook = true
method_type = @method_type
define_method(id) do |*args|
orig_method.bind(self).call(*args).tap do
puts "That was #{method_type}"
end
end
@bypass_method_added_hook = false
end
end
...您可以用来扩展一个类...
class Thing
extend FunNotFun
fun
def f1
puts "hey"
end
notfun
def f2
puts "hey"
end
end
......结果:
Thing.new.f1
# => hey
# => That was fun
Thing.new.f2
# => hey
# => That was not fun
但是请参阅下面的行以获得更好的方法。
注释(请参阅 normalocity 的答案)不太麻烦,并且作为一个常见的 Ruby 习惯用法,将更容易地传达您的代码意图。以下是使用注释的方法:
module FunNotFun
def fun(method_id)
wrap_method(method_id, "fun")
end
def notfun(method_id)
wrap_method(method_id, "not fun")
end
def wrap_method(method_id, type_of_method)
orig_method = instance_method(method_id)
define_method(method_id) do |*args|
orig_method.bind(self).call(*args).tap do
puts "That was #{type_of_method}"
end
end
end
end
在使用中,注解出现在方法定义之后,而不是之前:
class Thing
extend FunNotFun
def f1
puts "hey"
end
fun :f1
def f2
puts "hey"
end
notfun :f2
end
结果是一样的:
Thing.new.f1
# => hey
# => That was fun
Thing.new.f2
# => hey
# => That was not fun