加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby – 如何动态使用细化

发布时间:2020-12-17 03:50:23 所属栏目:百科 来源:网络整理
导读:试图理解这种“改进”业务. 我正在制作一个改进核心类的模块: module StringPatch refine String do def foo true end endend 然后一个类使用细化 class PatchedClassendPatchedClass.send :using,StringPatch 我收到此错误: RuntimeError: Module#using i
试图理解这种“改进”业务.

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

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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读