4

I'm trying to override Rails' "fields_for" method, which I'm currently doing as follows:

module ActionView::Helpers::FormHelper
  include ActionView::Helpers::FormTagHelper

  alias_method :original_fields_for, :fields_for

  def fields_for(<my arguments>)
    # Some extra stuff
    # ...
    output.safe_concat original_fields_for(<my other arguments>)
  end

end

The functionality works just fine, but I'm starting to suspect that my use of alias_method isn't the most elegant. Most especially, if I were to package this functionality into a gem, and there were another gem that overrode fields_for, am I write in thinking either my new fields_for OR the alternate fields_for would be skipped?

Assuming so, what's the correct way to go about slapping in some extra functionality to an existing rails method?

Cheers...

4

1 回答 1

3

这似乎正是应有的情况alias_method_chain(尽管我不知道它是否可以在模块上工作 - 只在 AR::Base 上使用过)

你只要做

module ActionView::Helpers::FormHelper
    include ActionView::Helpers::FormTagHelper

    alias_method_chain :fields_for, :honeypot

    def fields_for_with_honeypot(<my arguments>)
        # Some extra stuff
        # ...
        output.safe_concat fields_for_without_honeypot(<my other arguments>)
    end
end

这样做的有趣想法fields_for,但它应该工作。

您应该注意围绕 a_m_c 的一个小争议 - 这篇文章很好地总结了它http://erniemiller.org/2011/02/03/when-to-use-alias_method_chain/

在这种情况下,我认为您不能使用super,因为您想在不修改调用代码/视图的情况下对 form_for 进行猴子补丁。

于 2012-06-14T21:14:52.737 回答