0
module Typecast
class DSL
def self.call(&blk)
new.instance_eval(&blk)
end
def new_age(val)
p val
end
end
def typecast(&blk)
DSL.call(&blk)
end
private :typecast
end
class Person
include Typecast
def age=(new_age)
typecast do
new_age :integer
end
end
end
Person.new.age = 10
# test.rb:33: syntax error, unexpected ':', expecting keyword_end
# new_age :integer
Ruby返回此錯誤是因爲它知道new_age
是在方法參數中定義的局部變量。所以,當我改變Person
類這樣的:可變範圍干擾Ruby中的DSL
class Person
include Typecast
def age=(new_val)
typecast do
new_age :integer
end
end
end
紅寶石現在返回預期:integer
。
我的問題是,我該如何阻止局部變量干擾instance_eval
塊?
是的,我知道這一點。我想知道是否有辦法避免這樣做。我想改變'typecast'塊的綁定/範圍 – RyanScottLewis 2011-05-02 10:57:16