[英]Ruby instance_eval and const_missing
我想在instance_eval
调用const_missing
,但是似乎缺少了一些东西:
class A
def self.const_missing(c)
puts "Constant missing: #{c}"
end
def method_missing(m, *args, &block)
puts "Method missing: #{m}"
end
end
# Works:
a = A.new
a.myMethod # OK: "Method missing: myMethod"
a.MYCONST # Sort of OK: "Method missing: MYCONST"
# Doesn't work
a.instance_eval {
myMethod # OK: "Method missing: myMethod"
MYCONST # uninitialized constant MYCONST (NameError)
}
问: instance_eval
中的const_missing
调用在哪里? 如何将其重定向到A
类? (如果这很重要,则为Ruby 1.9.3)
上下文:我正在写一个小的DSL,其中大写字母用作状态名称。
DSL.evaluate {
ENTER_STATE_A
WAIT_FOR_INPUT
}
这些应该映射到方法,但是我想保持它们大写。
您正在尝试访问一个带a.MYCONST
的常量,该常量被ruby解释为一种方法。 相反,您需要在访问类本身的同时使用::
,而不是该类的实例:
a = A.new
a.instance_eval {
self::class::MYCONST # => Constant missing: MYCONST
}
这似乎在调用时MYCONST
内instance_eval
它被捉住Object.const_missing
。 例如,如果覆盖它,您将看到以下行为:
def Object.const_missing(c)
puts "Constant missing: #{c}"
end
a = A.new
a.instance_eval {
MYCONST # => Constant missing: MYCONST
}
我不建议您这样做。 我只是为了说明这一点而已。
请注意,当您这样做
a.MYCONST
您Method missing: MYCONST
(而不是Constant missing: MYCONST
)。
您应该执行以下操作:
a.instance_eval {
myMethod
A::MYCONST
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.