利用module_eval,Ruby可以读入一段代码,把它加入到正在运行的系统之中。这简直太dynamic了。如下面的例子:
#定义一个类
class TestClass
end
#定义一字符串
code = %q{ def hello() " Cool, isn't?" end }
#让code立刻生效
TestClass.module_eval(code)
TestClass.new.hello()
这段代码将输出“Cool, isn't?”。module_eval在RoR中得到广泛的运用,比如下面这段在RoR中常见的代码
class WeblogController
没有评论:
发表评论