Alias_method, alias_method_chain and self.included

I find it hard to understand alias_method

/ alias_method_chain

. I have the following code:

module ActionView::Helpers
  module FormHelper

    alias_method :form_for_without_cherries, :form_for

    def form_for(record, options = {}, &proc)
      output = 'with a cherry on top'.html_safe
      output.safe_concat form_for_without_cherries(record, options = {}, &proc)
    end
  end
end

      

This does exactly what I want - add "cherry on top" to the beginning of any call form_for

.

But I understand that this is not good code for several reasons. First, it will not be linked to any other overrides form_for(?)

, so if I wrote a second method form_for

that added "and another cherry on top" it would not show up. And secondly, alias_method

and alias_method_chain

are deprecated solutions of sorta and I have to use self.included

and send to module instead.

But I can't get self.included

to call this method form_for

- it just calls the parent call. Here's what I'm trying:

module CherryForm
  def self.included(base)
    base.extend(self)
  end

  def form_for(record, options = {}, &proc)
    output = 'with a cherry on top'.html_safe
    output.safe_concat super(record, options = {}, &proc)
  end 
end

ActionView::Helpers::FormHelper.send(:include, CherryForm)

      

My solution above works, but I have a suspicion that this is the wrong way to do things. If any ruby ​​veterans could show me a more elegant way to do this - and / or why the second solution is not called - I'd appreciate it.

+3


source to share


1 answer


When you disarm something, you must override the method, because there is no super for inheritance (so you cannot use the second piece of code).

Copying the current implementation of the method and adding your own is just a request for trouble, so this is where alias_method comes in.

alias_method :form_for_without_cherries, :form_for

      



It actually creates a clone of the original method, which you can use super instead. The fact that you cannot link monkey patches is not a bug, it is a feature.

The raias alias_method_chain method is indeed deprecated, but only because it was a bad idea to begin with. However, alias_method is a pure ruby ​​method and, if used correctly, can provide an elegant way to decapitate your code, so I'm sure it won't go away anytime soon.

+4


source







All Articles