诗歌rails之 alias_method magic

1. alias_method

Makes new_name a new copy of the method old_name . This can be used to retain access to methods that are overridden.

Ruby代码
  1. module Mod
  2. alias_method :orig_exit, :exit # Without alias_method, you have no way to access orig exit.
  3. def exit(code=0)
  4. puts "Exiting with code #{code}"
  5. orig_exit(code)
  6. end
  7. end
  8. include Mod
  9. exit(99)

produces:

Ruby代码
  1. Exiting with code 99

2. alias_method_chain


How this method arise? Yes, I guess always we will need to do this whenever we want to enhance a method.

Ruby代码
  1. alias_method :perform_action_without_benchmark, :perform_action # retain access to old method
  2. alias_method :perform_action, :perform_action_with_benchmark

The following do the same thing.

Ruby代码
  1. alias_method_chain :perform_action, :benchmark

Take a look at the source code:

Ruby代码
  1. # File active_support/core_ext/module/aliasing.rb, line 23
  2. def alias_method_chain(target, feature)
  3. # Strip out punctuation on predicates or bang methods since
  4. # e.g. target?_without_feature is not a valid method name.
  5. aliased_target, punctuation = target.to_s.sub(/([?!=])$/, ''), $1
  6. yield(aliased_target, punctuation) if block_given?
  7. with_method, without_method = "#{aliased_target}_with_#{feature}#{punctuation}", "#{aliased_target}_without_#{feature}#{punctuation}"
  8. alias_method without_method, target
  9. alias_method target, with_method
  10. case
  11. when public_method_defined?(without_method)
  12. public target
  13. when protected_method_defined?(without_method)
  14. protected target
  15. when private_method_defined?(without_method)
  16. private target
  17. end
  18. end

And it's a enhancement module for benchmarking.

Ruby代码
  1. module Benchmarking
  2. def self.included(base)
  3. base.extend(ClassMethods)
  4. base.class_eval do
  5. alias_method_chain :perform_action, :benchmark
  6. alias_method_chain :render, :benchmark
  7. end
  8. end
  9. ..... # where we difine perform_action_with_benchmark and render_with_benchmark

Dynamic language is cool! It makes enhancing easily, what you just need to do is:

Ruby代码
  1. ActionController::Base.class_eval do
  2. include ActionController::Flash
  3. include ActionController::Benchmarking
  4. include ActionController::Caching
  5. ...

And that's why DHH said, Rails 不是个庞然大物

posted @ 2009-07-22 18:05  麦飞  阅读(568)  评论(0编辑  收藏  举报