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