Delegate是一种应用composite来代替extend的机制,可以有效地降低代码的耦合性。

Rails 2.2增加了delegate方法,可以十分方便地实现delegate机制。

01.def delegate(*methods)
02. options = methods.pop
03. unless options.is_a?(Hash) && to = options[:to]
04. raise ArgumentError, "Delegation needs a target. Supply an options hash with a :to key as the last argument (e.g. delegate :hello, :to => :greeter)."
05. end
06.
07. if options[:prefix] == true && options[:to].to_s =~ /^[^a-z_]/8. raise ArgumentError, "Can only automatically set the delegation prefix when delegating to a method."9. end
10.
11. prefix = options[:prefix] && "#{options[:prefix] == true ? to : options[:prefix]}_"
12.
13. methods.each do |method|
14. module_eval(<<-EOS, "(__DELEGATION__)", 1)
15. def #{prefix}#{method}(*args, &block)
16. #{to}.__send__(#{method.inspect}, *args, &block)
17. end
18. EOS
19. end
20.end

delegate方法首先检查传入的参数,正确参数形式为:method1, :method2, ..., :methodN, :to => klass[, :prefix => prefix]

delegate要求参数的最后必须是一个Hash,:to表示需要代理的类,:prefix表示代理的方法是否要加前缀,如果:prefix => true,则代理的方法名为klass_method1,

klass_method2, ..., klass_methodN,如果:prefix => prefix (prefix为string),则代理的方法名为prefix_method1, prefix_method2, ..., prefix_methodN。

最终通过module_eval动态生成每个方法定义。通过__send__方法调用:to类的方法。

来看看调用的例子:

简单的调用:

01.class Greeter < ActiveRecord::Base
02. def hello() "hello" end
03. def goodbye() "goodbye" end
04.end
05.
06.class Foo < ActiveRecord::Base
07. delegate :hello, :goodbye, :to => :greeter
08.end
09.
10.Foo.new.hello # => "hello"
11.Foo.new.goodbye # => "goodbye"

增加:prefix => true:

1.class Foo < ActiveRecord::Base
2. delegate :hello, :goodbye, :to => :greeter, :prefix => true
3.end
4.
5.Foo.new.greeter_hello # => "hello"
6.Foo.new.greeter_goodbye # => "goodbye"

自定义前缀名:

1.class Foo < ActiveRecord::Base
2. delegate :hello, :goodbye, :to => :greeter, :prefix => :foo
3.end
4.
5.Foo.new.foo_hello # => "hello"
6.Foo.new.foo_goodbye # => "goodbye"

ruby的动态性再一次发挥了强大的功能!

转自:http://www.cnblogs.com/orez88/articles/1717438.html

rails delegate机制的更多相关文章

  1. iOS消息传递机制

    每个应用或多或少都由一些需要相互传递消息的对象结合起来以完成任务.在这篇文章里,我们将介绍所有可用的消息传递机制,并通过例子来介绍怎样在苹果的框架里使用.我们还会选择一些最佳范例来介绍什么时候该用什么 ...

  2. IOS OS X 中集中消息的传递机制

    1 KVO (key-value Observing) 是提供对象属性被改变是的通知机制.KVO的实现实在Foundation中,很多基于 Foundation 的框架都依赖与它.如果只对某一个对象的 ...

  3. IOS开发之delegate和Notification的区别

    delegate针对one-to-one关系,并且reciever可以返回值给sender: notification 可以针对one-to-one/many/none,reciever无法返回值给s ...

  4. Gradle 用法总结

    用过android studio的对gradle应该都不陌生了,gradle文件的基本配置大同小异,略做了解使用应该是没什么问题了.但是深入细致的了解一下对于理解项目还是很有帮助的,尤其是遇到一些配置 ...

  5. Android Gradle 经验总结

    用过android studio的对gradle应该都不陌生了,gradle文件的基本配置大同小异,略做了解使用应该是没什么问题了.但是深入细致的了解一下对于理解项目还是很有帮助的,尤其是遇到一些配置 ...

  6. [Tomcat] Tomcat的classloader

    定义 同其他服务器应用一样,tomcat安装了各种classloader(classes that implement java.lang.ClassLoader) Bootstrap | Syste ...

  7. 如何给开源的DUILib支持Accessibility

    最近的工作是给开源的DUILib支持Accessibility, 一些经验记录并分享下. 微软的Accessibility其实Windows平台上一个挺重要的东西, 尽管在国内不受重视,但是如果你的软 ...

  8. 李洪强iOS经典面试题135-Objective-C

    可能碰到的iOS笔试面试题(5)--Objective-C 面试笔试都是必考语法知识的.请认真复习和深入研究OC. Objective-C 方法和选择器有何不同?(Difference between ...

  9. Gradle学习系列之三——读懂Gradle语法

    在本系列的上篇文章中,我们讲到了创建Task的多种方法,在本篇文章中,我们将学习如何读懂Gradle. 请通过以下方式下载本系列文章的Github示例代码: git clone https://git ...

随机推荐

  1. python Nosql-redis 连接、管道

    非关系型数据库和关系型数据库的差别: 非关系型数据库的优势: 性能NOSQL是基于键值对的,可以想象成表中的主键和值的对应关系,而且不需要经过SQL层的解析,所以性能非常高. 可扩展性同样也是因为基于 ...

  2. Juel Getting Started

    Getting Started The JUEL distribution contains the following JAR files: juel-api-2.2.x.jar - contain ...

  3. hdu 1115(多边形重心问题)

    Lifting the Stone Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others ...

  4. [git] warning: LF will be replaced by CRLF | fatal: CRLF would be replaced by LF[ git 处理和修改行结束符(CRLF和LF)]

    我自己的设置是: [core] autocrlf = false[core] safecrlf = true 取消自动转换CRLF(上图中选的是commit as is),但是有提交前混用检查 本人用 ...

  5. SyntaxError: Non-ASCII character '\xe7' in file 错误的解决方法

    在代码开头写下面的定义即可 #encoding:utf-8

  6. 计蒜客 30996.Lpl and Energy-saving Lamps-线段树(区间满足条件最靠左的值) (ACM-ICPC 2018 南京赛区网络预赛 G)

    G. Lpl and Energy-saving Lamps 42.07% 1000ms 65536K   During tea-drinking, princess, amongst other t ...

  7. HDU 5938 Four Operations 【字符串处理,枚举,把数字字符串变为数值】

    Problem Description Little Ruins is a studious boy, recently he learned the four operations! Now he ...

  8. Python与数据结构[3] -> 树/Tree[1] -> 表达式树和查找树的 Python 实现

    表达式树和查找树的 Python 实现 目录 二叉表达式树 二叉查找树 1 二叉表达式树 表达式树是二叉树的一种应用,其树叶是常数或变量,而节点为操作符,构建表达式树的过程与后缀表达式的计算类似,只不 ...

  9. 【费马小定理+矩阵快速幂】HDU4549——M斐波那契数列

    [题目大意] M斐波那契数列F[n]是一种整数数列,它的定义如下:F[0] = aF[1] = bF[n] = F[n-1] * F[n-2] ( n > 1 )现在给出a, b, n,求出F[ ...

  10. (转)MOMO的Unity3D研究院之深入理解Unity脚本的执行顺序(六十二)

    http://www.xuanyusong.com/archives/2378 Unity是不支持多线程的,也就是说我们必须要在主线程中操作它,可是Unity可以同时创建很多脚本,并且可以分别绑定在不 ...