RubyDSL特点分析介绍

Ruby语言是一个应用灵活的解释型脚本语言。对于一个编程人员来说,Ruby DSL是一个功能强大的工具。下面我们就来一起看看Ruby DSL特点介绍。#t#

站在用户的角度思考问题,与客户深入沟通,找到西安网站设计与西安网站推广的解决方案,凭借多年的经验,让设计与互联网技术结合,创造个性化、用户体验好的作品,建站类型包括:成都网站建设、网站制作、企业官网、英文网站、手机端网站、网站推广、国际域名空间、网络空间、企业邮箱。业务覆盖西安地区。

在rails里面,我们可以用很方便的声明方式来定义model之间的关联关系,Ruby DSL特点例如:

  1. class Topic < Active
    Record::Base
       
  2. has_many :posts   
  3. belongs_to :user   
  4. end   
  5. class Topic < Active
    Record::Base
     
  6. has_many :posts  
  7. belongs_to :user  
  8. end 

那has_many和belongs_to究竟是什么东西呢?其实他们是Topic类的class method,Ruby DSL特点的标准写法是: 

  1. class Topic < ActiveRecord::Base   
  2. Topic.has_many(:posts)   
  3. Topic.belongs_to(:user)   
  4. end   
  5. class Topic < ActiveRecord::Base 
  6. Topic.has_many(:posts)  
  7. Topic.belongs_to(:user)  
  8. end 

那么has_many可以给我们带来什么呢?类方法has_many在被执行的时候,给Topic的对象实例添加了一系列方法:posts, posts<<, orders.push......等等。所以当我们在model里面声明has_many,belongs_to等对象关系的时候,一系列相关的对象方法就被自动添加进来了。

既然明白了rails的小把戏,让我们来自己试试看吧:

 
 
 
  1. module M   
  2. def self.included(c)   
  3. c.extend(G)   
  4. end   
  5. module G   
  6. def generate_method(*args)   
  7. args.each do |method_name|   
  8. define_method(method_name) 
    { puts method_name }   
  9. end   
  10. end   
  11. end   
  12. end   
  13. class C   
  14. include M   
  15. generate_method :method1, :method2   
  16. end   
  17. c = C.new   
  18. c.method1   
  19. c.method2   
  20. module M  
  21. def self.included(c)  
  22. c.extend(G)  
  23. end  
  24. module G  
  25. def generate_method(*args)  
  26. args.each do |method_name|  
  27. define_method(method_name) 
    { puts method_name }  
  28. end  
  29. end  
  30. end  
  31. end  
  32. class C  
  33. include M  
  34. generate_method :method1, :method2  
  35. end  
  36. c = C.new  
  37. c.method1  
  38. c.method2 

我们定义了一个声明generate_method,可以接受多个symbol,来动态的创建同名的方法。现在我们在类C里面使用这个声明:generate_method :method1, :method2,当然我们需要include模块M。为什么rails的model不需要include相关的模块呢?当然是因为Topic的父类ActiveRecord::Base已经include了模块Associations了。

类C通过include模块M,调用了模块M的一个included回调接口,让类C去extend模块G,换句话来说就是,通过include模块M,来给类C动态添加一个类方法generate_method。

这个generate_method被定义在模块G当中,它接受一系列参数,来动态创建相关的方法。于是我们就实现了这样的DSL功能:

通过在类C里面声明generate_method :method1, :method2,让类C动态的添加了两个实例方法method1,method2,是不是很有意思?

实际上rails的对象关联声明也是以同样的方式实现的。

以上就是对Ruby DSL特点的分析介绍。

当前文章:RubyDSL特点分析介绍
当前URL:http://www.zyruijie.cn/qtweb/news13/463.html

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

广告

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