何时使用`method_missing` [英] When to use `method_missing`

查看:63
本文介绍了何时使用`method_missing`的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中,方法roar未在类Lion中定义,但仍可以使用method_missing调用.

In the code below, method roar is not defined in class Lion, but still can be called using method_missing.

class Lion
  def method_missing(name, *args)
    puts "Lion will #{name}: #{args[0]}"
  end
end

lion = Lion.new
lion.roar("ROAR!!!") # => Lion will roar: ROAR!!!

在哪些情况下以及如何使用此method_missing?而且使用安全吗?

In which situations and how should I use this method_missing? And is it safe to use?

推荐答案

使用完全是安全,只要您以预期的方式使用它并且不会被带走.毕竟,并非您能做的一切都值得做.

It's entirely safe to use provided you use it in expected ways and don't get carried away. Not everything you can do is worth doing, after all.

method_missing的优点是您可以以独特的方式应对各种事情.

The advantage of method_missing is you can respond to all kinds of things in unique ways.

缺点是您不会宣传自己的能力.希望您respond_to?进行其他操作的其他对象将无法得到确认,并且可能以您不希望使用的方式对待您的自定义对象.

The disadvantage is you don't advertise your capabilities. Other objects that expect you to respond_to? something will not get confirmation and might treat your custom object in ways you don't intend.

对于构建领域特定语言并在组件之间提供非常松散的粘合,这种事情非常宝贵.

For building Domain Specific Languages and providing very loose glue between components, this sort of thing is invaluable.

Ruby是一个很好的例子,它是Ruby OpenStruct 类.

A great example of where this is a good fit is the Ruby OpenStruct class.

这篇关于何时使用`method_missing`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆