我想打電話給const_missing
在instance_eval
,但似乎失去了一些東西:紅寶石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)
}
問:在什麼地方const_missing
呼叫在instance_eval
去?如何將它重定向到類A
? (Ruby 1.9.3如果這件事很重要)
上下文:我正在寫一個小型DSL,其中大寫字母用作州名。
DSL.evaluate {
ENTER_STATE_A
WAIT_FOR_INPUT
}
這些應該映射到方法,但我想保持它們的大寫。
如果您的Ruby DSL需要違反已建立的[Ruby語法](https://en.wikibooks.org/wiki/Ruby_Programming/Syntax/Variables_and_Constants#Constants)來定義常量,那麼您正在挖掘一個巨人孔。 – anothermh
這就是爲什麼我想在instance_eval內真正發生任何變化的原因。 DSL文件在定義良好的階段加載,不要與代碼混合使用。 –