The append_features method of Module

本文探讨了Ruby中如何通过覆盖append_features方法为特定类添加来自模块的单例方法。通过具体示例代码展示了这一过程,并强调了调用super的重要性。
In the same way that the class could include some singleton methods,the Module could include some singleton methods,too.But if we implement a class which include a Module which contians some singleton methods,does these methods become to the class's singleton methods?The answer is 'no'.There is a hook called append_features that we can override.It's called with a parameter that is the destination class or module.For an example of its use,see the following codes:
ruby 代码
 
  1. module MyMod  
  2.   def MyMod.append_features(someClass)  
  3.     def someClass.modmeth  
  4.       puts "Module (class) method"  
  5.     end  
  6.     super  
  7.   end  
  8. end  
  9. class AppendFeatures  
  10.   include MyMod  
  11.   def initialize  
  12.       
  13.   end  
  14. end  
  15.   
  16. AppendFeatures.modmeth  

Note:
you should call the "super" when you override the append_features method.

It's very interesting.
These code copy from the <ruby way=""> book.</ruby>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值