Ruby的method_missing
用过ruby人对method_missing肯定不陌生,通常我们利用这一神技来实现调用不存在的方法,以便进行回调,利用它可以很方便的实现我们自己的DSL。
在学习method_missing之前,先理解下ruby方法调用过程
当ruby对象执行某一方法时,他需要找到这个方法,其查找流程如下:
1、查询当前对象的实例方法
2、查找当前对象所有模块,看是否有该方法
3、查找该对象的父类及父类模块(就是找他爹,他爹没有,再找它爷。。。)
4、如果这个对象很不幸没爹,那就直接到Object中找
5、到BasicObject中查找
如果还没找到,调用内核的method_missing方法,最终丢出NoMethodError
由上可知,method_missing是方法调用的最后一道防线,我们可以把method_missing理解为“方法找不到时,该做什么”
所以,我们可以在方法查询的任何位置通过重写method_missing的方式告诉ruby,“哥们,这方法如果没找到,就这样做。。。”
一、方法代理
方法代理使用的比较多的,通过method_missing让当前对象使用另外一个类的方法 举例:
class A def do_this p "this is class A" end end class B def initialize @proxy = A.new end def method_missing(method_name, *args, &block) p "this is class B" @proxy.do_this end end b = B.new b.do_this
b在查找do_this方法时,由于找不到,所以进入我们重写的method_missing中,在这里我们 通过class的实例对象proxy来执行A中的do_this方法。
二、编写DSL
通过上面的例子,可以知道method_missing可以对不存在的方法进行拦截,然后做我们想做 的事,这就为DSL的编写提供了很大的便利,我们在method_missing中对我们要执行的方法 进行解析,判断是不是满足我们所定义的语法等等,然后进行我们需要的操作,很多自动化测试框架就是使用这种方式的,通过定义自己的DSL可以让代码更具业务化。
- method_missing,一个 Ruby 程序员的梦中情人
- Ruby的method_missing可以定义client调用不存在的方法时的行为
- Ruby China中method_missing和define_method剖析
- ruby-method_missing
- [Ruby笔记]21.Ruby public_method_defined? 以及 method_missing
- win10写的程序在win7下面崩溃的问题 CLR20r3 MissingMethodException
- System.MissingMethodException之引用的dll版本号不对
- 使用gem安装rails,付解决It seems your ruby installation is missing psych (for YAML output).
- org.mockito.exceptions.misusing.MissingMethodInvocationException
- Ruby 中的各种变量(local/instance/class/global variable and assignment method)
- “System.MissingMethodException: 找不到方法” 错误的解决方法
- Ruby Meta Programming: define_method or class_eval
- Ruby on Rails,使用gem安装rails,付解决It seems your ruby installation is missing psych (for YAML output).
- .net 中使用Excel library 11.0 COM Workbooks.Open 出现错误:System.MissingMethodException: 找不到方法
- 调用Type.InvokeMember()时出现MissingMethodException
- [Ruby笔记]22.Ruby :: namespace 以及 instance method 与class method
- 关于ruby的methods、instance_methods、method三者的区别
- net报“System.MissingMethodException: Method not found(找不到方法)”错误的解决方法
- The method getContextPath() from the type HttpServletRequest refers to the missing type
- The method contains(CharSequence) from the type String refers to the missing type CharSequence错误解决方法