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

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

    I'm not sure if it's gone out of style with Rails 3 or not, but it is still actively used in versions before that.

    You use it to inject some functionality before (or after) a method is called, without modifying any place that calls that method. See this example:

    module SwitchableSmtp
      module InstanceMethods
        def deliver_with_switchable_smtp!(mail = @mail)
          unless logger.nil?
            logger.info  "Switching SMTP server to: #{custom_smtp.inspect}" 
          end
          ActionMailer::Base.smtp_settings = custom_smtp unless custom_smtp.nil?
          deliver_without_switchable_smtp!(mail = @mail)
        end
      end
      def self.included(receiver)
        receiver.send :include, InstanceMethods
        receiver.class_eval do
          alias_method_chain :deliver!, :switchable_smtp
        end
      end
    end
    

    That's an addition to ActionMailer to allow swapping out of the SMTP settings on each call to deliver!. By calling alias_method_chain you are able to define a method deliver_with_switchable_smtp! in which you do your custom stuff, and call deliver_without_switchable_smtp! from there when you're done.

    alias_method_chain aliases the old deliver! to your new custom method, so the rest of your app doesn't even know deliver! now does your custom stuff too.

提交回复
热议问题