惠州有哪些做网站的公司,wordpress改foot图标,计算机专业做网站运营,网站设计怎么做超链接对于alias, alias_method, alias_method_chain的深入理解是有益的#xff0c;因为rails3的源码里很多地方使用了alias_method_chain的魔法。 有人评论说alias_method_chain使用的过多不好#xff0c;具体怎么不好#xff0c;是后话了#xff0c;这篇文章集中在理解这3个方法…对于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 nila A.new #A:0xb7ef5234 a.m1m1 nila.m2m1 nil在使用的时候注意原有的方法名在最后位置用空格分开。2. alias_method作用和alias差不多是Module的一个私有实例方法只能用于给方法起别名并且参数只能是字符串或者符号alias后面跟的直接是方法名不是字符串也不是符号。例子class B def b p b end alias_method :c, :bend Bb B.new #B:0xb7ee75bcb.cb nilb.bb 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, :m2end Aa A.new #A:0xb7bd9820a.m1do something befor m1m1do 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.newa.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这样我们就搞定了。
相关文章: