如何在ruby优化之间共享代码?
module Ext refine Hash do def foo puts :in_foo end def bar puts :in_bar foo end end end module Test using Ext Hash.new.bar end # in_bar # in_foo # => nil
这按预期工作。 但是如果我想通过使用include
在Hash
和Array
之间共享foo
和bar
,它就会失败。
module Shared def foo puts :in_foo end def bar puts :in_bar foo end end module Ext refine Hash do include Shared end refine Array do include Shared end end module Test using Ext Hash.new.bar end # in_bar # NameError: undefined local variable or method `foo' for {}:Hash
有没有办法在改进之间共享代码?
问题不在于分享。 完全摆脱Array
细化,你会产生相同的行为。
根据文件 :
优化分别在文件末尾或eval字符串结尾处有效。 改进在范围上是词汇。 当控制转移到范围之外时,细化被停用。 这意味着,如果您需要或加载文件或调用在当前范围之外定义的方法,则将停用细化。
也就是说,你的例子中失败的是refine do ⇒ include
。 该语言尚未准备好include
在refine
子句中。 也许将来有可能将该function提升到“实验”阶段。
如果你仍然认为你想依赖refinemenet,你可能会欺骗ruby(全局变量是为了清晰起见):
$ref = lambda do def foo puts :in_foo end public :foo def bar puts :in_bar foo end public :bar end module Ext refine ::Hash do $ref.call end end module Test using Ext ::Hash.new.bar end #⇒ in_bar #⇒ in_foo