Ruby 求解答,关于 method_missing

EdwardRuby · 2012年11月06日 · 最后由 EdwardRuby 回复于 2012年11月07日 · 2639 次阅读

在《Ruby 编程语言》这本书中看到一段代码,演示生成一个规范的 html 文件内容。 代码如下 class XML def initialize(out) @out=out #hold the output end

def content(text) @out << text.to_s nil end

def comment(text) @out << "<!-- #{text} -->" nil end

def tag(wherename, attributes={}) puts wherename @out << "<#{wherename}"

attributes.each { |attr,value| @out << "#{attr}='#{value}'"}

if block_given? @out << '>' content = yield if content @out << content.to_s end @out << "</#{wherename}>" else @out << '/>' end end

alias method_missing tag

def self.generate(out, &block) XML.new(out).instance_eval(&block) end end

下面是使用这个类的一个例子。 XML.generate(STDOUT) do html do end end 结果会输出 我知道执行 html 这个未定义方法时会寻找到 method_missing 从而调用 tag 方法。 但是 tag 方法的第一个参数 wherename(书上是 tagname)是从何而来的,这个变量刚好对应了 html 方法的名字,这点我不大明白。 希望高手指教,谢谢!

alias :method_missing :tag 这个 alias 可以理解为重新定义了 method_missing 函数,当调用 method_missing 函数时实际调用的是 tag 函数。当方法未找到时调用的 method_missing 函数的第一个参数是函数名,实际调用的是 tag(函数名,参数…),而缺失函数的函数名就是那个 html 方法名。 例如,我在 block 里面调用了 html(参数…),解释器发现没有找到这个函数,这时候就会调用 method_missing(:html, 参数…),也就是调用了 tag(:html, 参数…)

#1 楼 @qinix 谢谢解答!在书上没看到这点。

需要 登录 后方可回复, 如果你还没有账号请 注册新账号