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

前端 未结 4 1852
陌清茗
陌清茗 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

    is it used at all?

    Seems so. It's a common practice among Rails developers

    when would you use alias_method_chain and why?

    Despite the warnings, alias_method_chain is still the main strategy used when injecting functionality to an existing method, at least was in Rails 2.x and is followed by many people extending it. Yehuda ought to remove alias_method_chain from rails 3.0 to say from his posts and comments in Rails tickets. It is still used by many extensions that add custom behavior at certain points of the execution, such as loggers, error reporters, benchmarking, data injection, etc.

    IMO, the best alternative is to include a module, thus you have decoration over delegation. (For example, follow example 4 in this post). That way you can alter the objects even individually if you'd like, without polluting the class' methods. The downside to this is that the method lookup chain increases for each module you inject, but this is what modules are for anyway.

    Very interesting question, will keep a look on what other people think about it.

提交回复
热议问题