试图理解这种“改进”业务.
我正在制作一个改进核心类的模块:
module StringPatch refine String do def foo true end end end
然后一个类使用细化
class PatchedClass end PatchedClass.send :using,StringPatch
我收到此错误:
RuntimeError: Module#using is not permitted in methods
我怎样才能做到这一点?
我试图仅在某个范围内动态修补核心类.我想在类和实例范围中使补丁可用.
解决方法
据我所知,当在main中使用时,直到脚本结束时,细化才会生效,直到当前类/模块定义结束时才使用在类或模块中.
module StringPatch refine String do def foo true end end end class PatchedClass using StringPatch puts "test".foo end class PatchedClass puts "test".foo #=> undefined method `foo' for "test":String (NoMethodError) end
这意味着如果您设法在类或模块上动态调用,则会直接删除其效果.
class PatchedClass using StringPatch def foo "test".foo #=> true end end class PatchedClass def bar "test".foo end end patched = PatchedClass.new puts patched.foo #=> true puts patched.bar #=> undefined method `foo' for "test":String (NoMethodError)
对于你的问题,这discussion可能很有趣.看起来精简是有目的的,但我不知道为什么:
Because refinement activation should be as static as possible.