[英]Ruby refinements with instance_eval
I'd like to provide some refinements to a DSL.我想对 DSL 进行一些改进。 I'm able to get refinements working with this example:
我可以使用此示例进行改进:
module ArrayExtras
refine Array do
def speak
puts 'array!'
end
end
end
module MyUniverse
using ArrayExtras
class Thing
def initialize
[1].speak
end
end
end
MyUniverse::Thing.new
This prints out "array!"这会打印出“数组!” just fine.
正好。 But once I introduce
instance_eval
, the method can't be found:但是一旦我引入了
instance_eval
,就找不到该方法:
module MyUniverse
using ArrayExtras
class DSL
def initialize(&block)
instance_eval(&block)
end
end
end
MyUniverse::DSL.new do
[1].speak
end
I get a undefined method
speak' for [1]:Array (NoMethodError)`我为 [1]:Array (NoMethodError)` 得到了一个
undefined method
Is there a way to get refinements working within an instance_eval?有没有办法在 instance_eval 中进行改进?
Refinements are lexically scoped.细化是词法范围的。 You are activating the Refinement in the wrong lexical context.
您在错误的词法上下文中激活了 Refinement。 You need to activate it where you are calling the refined method:
您需要在调用精炼方法的地方激活它:
module ArrayExtras
refine Array do
def speak
puts 'array!'
end
end
end
module MyUniverse
class DSL
def initialize(&block)
instance_eval(&block)
end
end
end
using ArrayExtras
MyUniverse::DSL.new do
[1].speak
end
# array!
In some cases you can achieve it by using ArrayExtras
on the binding.在某些情况下,您可以通过在绑定上
using ArrayExtras
来实现它。
module MyUniverse
using ArrayExtras
class DSL
def initialize(&block)
block.binding.eval("using ArrayExtras")
instance_eval(&block)
end
end
end
MyUniverse::DSL.new do
[1].speak
end
This will however only work if you are not using your class in an instance, it only works if the binding
is a module or class context, otherwise the eval
will fail because main.using is permitted only at toplevel
.但是,这仅在您不在实例中使用您的类时才有效,仅当
binding
是模块或类上下文时才有效,否则eval
将失败,因为main.using is permitted only at toplevel
。
If you want to refine the ruby core BaseObject
, you need to modify it as below.如果要细化 ruby 核心
BaseObject
,则需要进行如下修改。
module ArrayExtras
refine ::Array do
def speak
puts 'array!'
end
end
end
It will be found in top level class.它将在顶级课程中找到。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.