gpt4 book ai didi

ruby-on-rails - ruby /rails : alias_method practices

转载 作者:数据小太阳 更新时间:2023-10-29 07:34:39 25 4
gpt4 key购买 nike

我正在尝试覆盖 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 中,并且有另一个 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,因为你想在不修改调用代码/ View 的情况下猴子修补 form_for。

关于ruby-on-rails - ruby /rails : alias_method practices,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10440631/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com