浅谈Ruby on Rails中的include和extend

从模块引入方法、变量,使得编程变得简单,扩展性愈强,比以往的类的继承更灵活。这样的引入,仿佛将一个方法块,复制了一份放到了你所引用的类或者模块里面。你完全可以将多个互不相干的类中相同的方法拿出来写到一个模块中,这样可以使得代码精简,符合Ruby的设计初衷,而且,使得你的程序更有条理。

Ruby on Rails常见用法

通常引用模块有以下3种情况:

1.在类定义中引入模块,使模块中的方法成为类的实例方法

这种情况是最常见的

直接 include 即可

2.在类定义中引入模块,使模块中的方法成为类的类方法

这种情况也是比较常见的

直接 extend 即可

3.在类定义中引入模块,既希望引入实例方法,也希望引入类方法

这个时候需要使用 include,

但是在模块中对类方法的定义有不同,定义出现在self.included块中

def self.included(c) ... end 中

Ruby on Rails实例讲解

Code

 
 
 
  1. #基类  
  2. module Base  
  3.   #显示  
  4.   def show  
  5.     puts "You came here!"  
  6.   end  
  7. end  
  8. class Car  
  9.   extend Base   #扩展了类方法,我们可以通过Car.show调用  
  10. end  
  11. class Bus  
  12.   include Base  #扩展了实例方法,可以通过Bus.new.show调用  
  13. end 

但是我们经常有这样的需要,希望基类足够强大,既可以扩展实例方法,也可以扩展类方法,Ruby on Rails同样提供了解决方案。

 
 
 
  1. Code  
  2. #基类  
  3. module Base  
  4.   def show  
  5.     puts "You came here!"  
  6.   end  
  7.  
  8.   #扩展类方法  
  9.   def self.included(base)  
  10.     def base.call  
  11.       puts "I'm strong!"  
  12.     end  
  13.     base.extend(ClassMethods)  
  14.   end  
  15.  
  16.   #类方法  
  17.   module ClassMethods  
  18.     def hello  
  19.       puts "Hello baby!"  
  20.     end  
  21.   end  
  22.      
  23. end  
  24.  
  25. class Bus  
  26.   include Base  
  27. end 

此时Bus已经具备了实例方法show,类方法:call 、hello,访问方式

 
 
 
  1. Bus.new.show  
  2. Bus.call  
  3. Bus.hello 

肯定也有人提出此类疑问,使用extend能够实现此功能不?

答案是:暂未找到,如您找到请明示,多谢!

我也曾经做过以下实验,结果没有成功,在此也张贴出来,希望能给您带来一些启示。

 
 
 
  1. Code  
  2. #基类  
  3. module Base  
  4.   def show  
  5.     puts "You came here!"  
  6.   end  
  7.     
  8.     #扩展实例方法  
  9.   def self.extended(base)  
  10.     base.extend(InstanceMethods)  
  11.   end  
  12.  
  13.   module InstanceMethods  
  14.     def love  
  15.       puts 'We are instances,loving each other!'  
  16.     end  
  17.   end  
  18.  
  19. end  
  20.  
  21. class Car  
  22.   extend Base  
  23. end 

但是这样,实例方法扩展失败,依然扩展了类方法

 
 
 
  1. Car.show  
  2. Car.love             #类方法  
  3. Car.new.love      #undefined method 'love'  

【编辑推荐】

  1. Ruby语言的发展趋势和启示
  2. Ruby on Rails为企业SOA做好准备了吗
  3. 脚本语言排行榜 PHP、Ruby和Python领先
  4. 让Ruby性能增加30%的改进方法分析
  5. 对Ruby VS Java误区的深度剖析

网站名称:浅谈Ruby on Rails中的include和extend
标题路径:http://www.shufengxianlan.com/qtweb/news29/419379.html

网站建设、网络推广公司-创新互联,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联