Ruby on Rails: alias_method_chain, what exactly does it do?

前端 未结 4 1844
陌清茗
陌清茗 2020-12-12 18:11

I\'ve tried reading through various blog posts that attempt to explain alias_method_chain and the reasons to use it and not use it. In particular, I took heed to:

ht

4条回答
  •  眼角桃花
    2020-12-12 18:57

    1 - is it still used at all?

    Apparently yes, alias_method_chain() is still used in Rails (as of version 3.0.0).

    2 - when would you use alias_method_chain and why?

    (Note: the following is largely based on the discussion of alias_method_chain() in Metaprogramming Ruby by Paolo Perrotta, which is an excellent book that you should get your hands on.)

    Let's start with a basic example:

    class Klass
      def salute
        puts "Aloha!"
      end
    end
    
    Klass.new.salute # => Aloha!
    

    Now suppose that we want to surround Klass#salute() with logging behavior. We can do that what Perrotta calls an around alias:

    class Klass
      def salute_with_log
        puts "Calling method..."
        salute_without_log
        puts "...Method called"
      end
    
      alias_method :salute_without_log, :salute
      alias_method :salute, :salute_with_log
    end
    
    Klass.new.salute
    # Prints the following:
    # Calling method...
    # Aloha!
    # ...Method called
    

    We defined a new method called salute_with_log() and aliased it to salute(). The code that used to call salute() still works, but it gets the new logging behavior as well. We also defined an alias to the original salute(), so we can still salute without logging:

    Klass.new.salute_without_log # => Aloha!
    

    So, salute() is now called salute_without_log(). If we want logging, we can call either salute_with_log() or salute(), which are aliases of the same method. Confused? Good!

    According to Perrotta, this kind of around alias is very common in Rails:

    Look at another example of Rails solving a problem its own way. A few versions ago, the Rails code contained many instances of the same idiom: an Around Alias (155) was used to add a feature to a method, and the old version of the method was renamed to something like method_without_feature(). Apart from the method names, which changed every time, the code that did this was always the same, duplicated all over the place. In most languages, you cannot avoid that kind of duplication. In Ruby, you can sprinkle some metaprogramming magic over your pattern and extract it into its own method... and thus was born alias_method_chain().

    In other words, you provide the original method, foo(), and the enhanced method, foo_with_feature(), and you end up with three methods: foo(), foo_with_feature(), and foo_without_feature(). The first two include the feature, while the third doesn't. Instead of duplicating these aliases all around, alias_method_chain() provided by ActiveSupport does all the aliasing for you.

提交回复
热议问题