试图理解这种“改进”业务.
我正在制作一个改进核心类的模块:
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.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。