当前位置: 首页 > news >正文

深入理解alias, alias_method和alias_method_chain

对于alias, alias_method, alias_method_chain的深入理解是有益的,因为rails3的源码里很多地方使用了alias_method_chain的魔法。 有人评论说alias_method_chain使用的过多不好,具体怎么不好,是后话了,这篇文章集中在理解这3个方法上面。

如果想转载本文,请注明出处,谢谢!请尊重别人的劳动成果,为构建丰富web原创内容做贡献!


1. alias
   Ruby里的关键字,用于定义方法或者全局变量的别名。 例子:
   class A
     def m1
       puts "m1"
     end
     alias m2 m1
    end
=> nil
a = A.new
=> #<A:0xb7ef5234>
 a.m1
m1
=> nil
a.m2
m1
=> nil

在使用的时候,注意原有的方法名在最后位置,用空格分开。

2. alias_method
作用和alias差不多,是Module的一个私有实例方法,只能用于给方法起别名,并且参数只能是字符串或者符号(alias后面跟的直接是方法名,不是字符串也不是符号)。例子:
class B
  def b
    p "b"
  end
  alias_method :c, :b
end
=> B
b = B.new
=> #<B:0xb7ee75bc>
b.c
"b"
=> nil
b.b
"b"
=> nil
注意,alias_method的参数必须是字符串或者是符号,并且用逗号分隔。

3. alias_method_chain
是ActiveSupport的一个公有实例方法。同样接受两个参数,可以是符号,也可以是字符串,但要注意一下第1个参数才是原始方法(alias_method的第2个参数是原始方法)。例子:
class A
  def m1
    puts 'm1'
  end
  def m1_with_m2
    puts "do something befor m1"
    m1_without_m2
    puts "do something after m2"
  end
  alias_method_chain :m1, :m2
end
=> A
a = A.new
=> #<A:0xb7bd9820>
a.m1
do something befor m1
m1
do something after m2
=> nil

上面的代码用alias或者alias_method也能完成:
class A  
  def m1  
    puts 'm1'  
  end
  alias m1_without_m2 m1  
  def m1_with_m2  
    puts 'do something else'  
    m1_without_m2  
  end  
  alias m1 m1_with_m2  
end

那么其原理也一目了然了:
a = A.new
a.m1
当调用m1的时候, m1_with_m2会执行,  在puts "do something befor m1"之后,执行m1_without_m2,这个时候是执行了真正的m1方法。 这样就形成了一个类似于AOP的行为。
也可以说,对外把m1方法隐藏起来了,对类外部,实际上把m1_with_m2改头换面已经成为了另一个方法,只是我们不知道而已,因为它还叫m1.

再来看看alias_method_chain的源码:
def alias_method_chain(target, feature) 
  # Strip out punctuation on predicates or bang methods since 
  # e.g. target?_without_feature is not a valid method name. 
  aliased_target, punctuation = target.to_s.sub(/([?!=])$/, ''), $1 
  yield(aliased_target, punctuation) if block_given?      
  with_method, without_method = "#{aliased_target}_with_#{feature}#{punctuation}", "#{aliased_target}_without_#{feature}#{punctuation}" 
  alias_method without_method, target 
  alias_method target, with_method       
  case 
    when public_method_defined?(without_method) 
      public target 
    when protected_method_defined?(without_method) 
      protected target 
    when private_method_defined?(without_method) 
      private target 
  end 
end
一个道理。

更实际的例子:
在一些rails比较老的系统里,搜索功能的日期选择可能会用到date_select,这个方法会生成类似于这样的页面元素:
search_form[start_from(1i)]年
search_form[start_from(2i)]月
search_form[start_from(3i)]日
把这样的参数传回去,就无法查询到对应的日期。这个时候我们需要在后台得到查询条件之后来处理日期,比如:
get_conditions 这个方法假如是得到页面查询条件的,它返回一个数组,这个时候我们可以定义:

def get_conditions_with_handle_date
  puts "你可以在get_conditions方法执行前干点别的,如果你愿意"
  get_conditions_without_handle_date
  puts "get_conditions执行完了,我们可以在其后干点别的,比如说处理日期"
  conditions.reject!{|condition|condition[0] =~ /\([1-3]i\)/}   # 把条件数组里的1i,2i,3i之类的去掉。
  conditions << ["? <= #{@model.table_name}.created_at", @search.start_from] if @search.start_from  #给搜索对象里添加正确的查询日期条件
  conditions << ["#{@model.table_name}.created_at < ?", @search.end_to + 1.day] if @search.end_to   #给搜索对象里添加正确的查询日期条件
end
  #然后实施魔法
  alias_method_chain :get_conditions, :handle_date

这样我们就搞定了。

相关文章:

  • golang包管理工具glide安装
  • 为寻求新增长点 山寨之父MTK发力Android
  • Use SourceLink enables a great source debugging experience
  • 【书籍推荐】Expert Oracle Practices
  • CodeForces-4C Registration system
  • 利用浏览器的搜索框作更多的事情
  • 键盘提示
  • 随机打乱一个数组的算法
  • 计算CPU的MIPS
  • ×××的特点
  • linux下ping命令出现ping: sendto: Network is unreachable
  • 小程序自定义pick(日期加时间组合)
  • 优化STP
  • 第 5 章 深入理解函数
  • 【140天】尚学堂高淇Java300集视频精华笔记(86-87)
  • Android系统模拟器绘制实现概述
  • CSS中外联样式表代表的含义
  • Java 多线程编程之:notify 和 wait 用法
  • Protobuf3语言指南
  • SpringBoot 实战 (三) | 配置文件详解
  • Yii源码解读-服务定位器(Service Locator)
  • 番外篇1:在Windows环境下安装JDK
  • 理清楚Vue的结构
  • 力扣(LeetCode)965
  • 你不可错过的前端面试题(一)
  • 前端面试之闭包
  • 设计模式走一遍---观察者模式
  • 腾讯大梁:DevOps最后一棒,有效构建海量运营的持续反馈能力
  • 译自由幺半群
  • TPG领衔财团投资轻奢珠宝品牌APM Monaco
  • ​如何防止网络攻击?
  • # Swust 12th acm 邀请赛# [ K ] 三角形判定 [题解]
  • $(function(){})与(function($){....})(jQuery)的区别
  • (1)虚拟机的安装与使用,linux系统安装
  • (DFS + 剪枝)【洛谷P1731】 [NOI1999] 生日蛋糕
  • (java)关于Thread的挂起和恢复
  • (javascript)再说document.body.scrollTop的使用问题
  • (NO.00004)iOS实现打砖块游戏(九):游戏中小球与反弹棒的碰撞
  • (第61天)多租户架构(CDB/PDB)
  • (论文阅读笔记)Network planning with deep reinforcement learning
  • (七)c52学习之旅-中断
  • (一) storm的集群安装与配置
  • (转载)Google Chrome调试JS
  • .NET Core工程编译事件$(TargetDir)变量为空引发的思考
  • .NET 常见的偏门问题
  • .NET 使用 XPath 来读写 XML 文件
  • .NET 应用架构指导 V2 学习笔记(一) 软件架构的关键原则
  • .Net 中的反射(动态创建类型实例) - Part.4(转自http://www.tracefact.net/CLR-and-Framework/Reflection-Part4.aspx)...
  • .Net程序帮助文档制作
  • .NET中统一的存储过程调用方法(收藏)
  • @NestedConfigurationProperty 注解用法
  • @requestBody写与不写的情况
  • [2544]最短路 (两种算法)(HDU)
  • [ai笔记9] openAI Sora技术文档引用文献汇总