浏览 1382 次
锁定老帖子 主题:让一个类include一个模块的几种方法
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
|
|
---|---|
作者 | 正文 |
发表时间:2009-09-22
最后修改:2009-09-22
module Test module ClassMethods def test_class p 'this is a class method' end end module InstanceMethods def test_ins p 'this is a instance method' end def method_missing self end end # def self.included(receiver) # receiver.extend ClassMethods # receiver.send :include, InstanceMethods # end end =begin rdoc Add instance methods =end # String.class_eval("include Test::InstanceMethods") # 's'.test_ins # => "this is a instance method" # String.send :include,Test::InstanceMethods # 's'.test_ins # => "this is a instance method" =begin rdoc Add class methods =end # class << String;include Test::ClassMethods;end # String.test_class # => "this is a class method" # String.extend Test::ClassMethods # String.test_class # => "this is a class method" 从上面的代码可以看出: class_eval和send :include,Module是一个作用, 都是将一个模块变成self类的实例方法. class <<和extend是一个作用, 都可以将一个模块变成self的类方法,都把Module的方法塞进了sefl类的metaclass里面. 声明:ITeye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
推荐链接
|
|
返回顶楼 | |