Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/54.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails Ruby/Rails:alias_方法实践_Ruby On Rails_Ruby_Rubygems_Alias Method - Fatal编程技术网

Ruby on rails Ruby/Rails:alias_方法实践

Ruby on rails Ruby/Rails:alias_方法实践,ruby-on-rails,ruby,rubygems,alias-method,Ruby On Rails,Ruby,Rubygems,Alias Method,我正试图覆盖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 # ...

我正试图覆盖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
module ActionView::Helpers::FormHelper
包括ActionView::Helpers::FormTagHelper
别名\方法:原始\字段\用于,:字段\用于
为()定义字段
#一些额外的东西
# ...
output.safe_concat原始_字段_for()
结束
结束
该功能运行得很好,但我开始怀疑我使用的alias_方法不是最优雅的。最特别的是,如果我将此功能打包到一个gem中,并且有另一个gem覆盖了字段(u),那么我是否认为我的新字段(u)或替代字段(u)将被跳过

假设是这样,对现有rails方法添加一些额外功能的正确方法是什么


干杯…

这似乎正是
alias\u method\u 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
module ActionView::Helpers::FormHelper
包括ActionView::Helpers::FormTagHelper
别名\u方法\u链:字段\u用于,:蜜罐
使用蜜罐()为蜜罐定义字段
#一些额外的东西
# ...
output.safe\u concat字段\u用于不带\u蜜罐的\u()
结束
结束
对的
字段执行此操作是一个有趣的想法,但它应该可以工作

有一个小争议围绕着一个你应该知道-这篇文章总结得很好


在这种情况下,我不认为您可以使用
super
,因为您希望在不修改调用代码/视图的情况下为表单添加修补程序。

为什么不创建一个新的表单生成器呢?嗨,Apnea-感谢您的回复。“一些额外的东西”涉及将蜜罐(在模型中定义)注入表单中。这是一个非常通用的功能&我希望它能在表单构建器中使用,我猜如果我指定一个特定的构建器,这是不可能的(例如,如果我指定“honeypot\u fields\u For”,它不会从formtastic/simple\u表单构建器中调用)我假设@apneding所说的是——从这个意义上说,你给了人们使用表单生成器的选择,而通过直接覆盖该方法,人们不可能不使用它