加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – Ruby / Rails:alias_method实践

发布时间:2020-12-17 02:17:48 所属栏目:百科 来源:网络整理
导读:我试图覆盖Rails的“fields_for”方法,我目前正在做如下: module ActionView::Helpers::FormHelper include ActionView::Helpers::FormTagHelper alias_method :original_fields_for,:fields_for def fields_for(my arguments) # Some extra stuff # ... ou
我试图覆盖Rails的“fields_for”方法,我目前正在做如下:

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

功能很好,但我开始怀疑我使用alias_method并不是最优雅的.最特别的是,如果我要将此功能打包到gem中,并且还有另一个宝石覆盖了fields_for,我是否会想到我的新fields_for或备用fields_for会被跳过?

假设是这样,将一些额外的功能用于现有的rails方法的正确方法是什么?

干杯…

解决方法

这看起来就像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而不修改调用代码/视图.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读