Ruby DSL特点分析介绍

开发 开发工具
我们希望大家通过对本文中介绍的Ruby DSL特点介绍,可以帮助大家提高对Ruby语言的了解程度,积累我们的编程经验。

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

责任编辑:曹凯 来源: 百度博客
相关推荐

2009-12-14 13:56:12

Ruby特点

2009-12-17 10:29:04

Ruby异常处理结构

2009-12-14 18:23:38

Ruby DSL测试

2009-12-14 18:14:27

Ruby DSL

2009-12-14 15:04:32

Ruby性能特点

2009-12-14 13:06:08

Ruby数字类型

2010-01-27 16:41:48

Android特点

2009-12-14 16:26:40

Ruby复制文件

2009-12-17 17:13:23

Ruby for Ec

2009-12-15 15:19:30

Ruby访问控制

2009-12-18 14:59:54

Ruby标识名

2009-12-15 11:31:53

Ruby self

2009-12-14 13:27:06

Ruby区间

2009-12-15 18:39:36

Ruby Active

2009-12-29 13:29:28

WPF Depende

2010-03-10 18:51:18

Python语言

2010-02-23 09:51:32

WCF MTOM

2009-12-24 10:09:33

WPF事件注册

2009-12-29 16:21:46

silverlight

2009-12-25 16:05:24

WPF 4.0特点
点赞
收藏

51CTO技术栈公众号