ruby – 如何动态使用细化

试图理解这种“改进”业务.

我正在制作一个改进核心类的模块:

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.

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...