Ruby DSL特点分析介绍
创始人
2024-06-15 20:11:24
0

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特点的分析介绍。

相关内容

热门资讯

如何允许远程连接到MySQL数... [[277004]]【51CTO.com快译】默认情况下,MySQL服务器仅侦听来自localhos...
如何利用交换机和端口设置来管理... 在网络管理中,总是有些人让管理员头疼。下面我们就将介绍一下一个网管员利用交换机以及端口设置等来进行D...
施耐德电气数据中心整体解决方案... 近日,全球能效管理专家施耐德电气正式启动大型体验活动“能效中国行——2012卡车巡展”,作为该活动的...
20个非常棒的扁平设计免费资源 Apple设备的平面图标PSD免费平板UI 平板UI套件24平图标Freen平板UI套件PSD径向平...
德国电信门户网站可实时显示全球... 德国电信周三推出一个门户网站,直观地实时提供其安装在全球各地的传感器网络检测到的网络攻击状况。该网站...
为啥国人偏爱 Mybatis,... 关于 SQL 和 ORM 的争论,永远都不会终止,我也一直在思考这个问题。昨天又跟群里的小伙伴进行...
《非诚勿扰》红人闫凤娇被曝厕所... 【51CTO.com 综合消息360安全专家提醒说,“闫凤娇”、“非诚勿扰”已经被黑客盯上成为了“木...
2012年第四季度互联网状况报... [[71653]]  北京时间4月25日消息,据国外媒体报道,全球知名的云平台公司Akamai Te...