覆盖Rails帮助者,可以使用原始内容 [英] Override rails helpers with access to original

查看:71
本文介绍了覆盖Rails帮助者,可以使用原始内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用Rails熟悉的助手,但是功能稍有改变.我的看法是,我希望能够做类似的事情:

I want to use rails' familiar helpers, but with slightly altered functionality. The way I see it, I want to be able to do something like:

module AwesomeHelper
  #... create alias of stylesheet_link_tag to old_stylesheet_link_tag
  def stylesheet_link_tag(*args)
    if @be_awesome
      awesome_stylesheet_link_tag *args
    else
      old_stylesheet_link_tag *args
    end
  end
end

我看到的方式有三种选择:

The way I see it, I have three options:

  1. 猴子修补程序:重新打开Rails帮助器模块.如果Rails团队更改了其助手模块的名称,那么我的代码将变得脆弱.不是不可克服的,但也不是理想的.
  2. 使用不同的方法名称:尝试坚持使用共轨接口可能是我的失败.我的更改可能会使其他开发人员感到困惑
  3. 分离方法(新)::不确定是否可行,或是否具有与1相同的缺点.将对此进行研究,但这可能是一个很好的起点.
  1. Monkey patching: Reopening the rails helper module. If the rails team ever change the name of their helper module, my code becomes a source of brittleness. Not insurmountable, but not ideal.
  2. Use different method names: Trying to stick to the common rails interface may be my downfall. My changes may become a source of confusion for other developers
  3. Detaching methods (new): Not sure whether this would work, or whether it would have the same drawbacks as 1. Will research this, but this might be a good starting point.

所以这里的问题是,我是坚持使用这些次优解决方案之一,还是有我没有考虑过的另一种方法?如果我选择选项3,有没有办法直接解决rails helper模块呢?

So the question here is, am I stuck with one of these sub-optimal solutions, or is there another way that I haven't considered? If I go for option 3, is there a way to do it without directly addressing the rails helper module?

(注意:我已经删除了上下文,因为它没有为问题添加任何内容.)

(Note: I have removed the context, as it adds nothing to the question.)

推荐答案

比您列出的任何选项都有更好的方法.只需使用super:

There's a better way than any of your listed options. Just use super:

module AwesomeHelper
  def stylesheet_link_tag(*sources)
    if @be_awesome
      awesome_stylesheet_link_tag *sources
    else
      super
    end
  end
end

在AwesomeHelper中重写stylesheet_link_tag将确保在调用stylesheet_link_tag时,Ruby在到达ActionView::Helpers::AssetTagHelper之前会在方法查找路径中遇到它.如果@be_awesometrue,您将负责并在此停止一切,否则,没有括号的对super的调用将透明地传递所有参数,直至Rails实现.这样,您就不必担心Rails核心团队在您身上四处移动!

Overriding stylesheet_link_tag in AwesomeHelper will ensure that, when stylesheet_link_tag gets invoked, Ruby will encounter it in the method lookup path before it hits ActionView::Helpers::AssetTagHelper. If @be_awesome is true, you get to take charge and stop things right there, and if not, the call to super without parentheses will transparently pass through all the arguments up to the Rails implementation. This way you don't have to worry about the Rails core team moving things around on you!

这篇关于覆盖Rails帮助者,可以使用原始内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆