代码之家  ›  专栏  ›  技术社区  ›  AlexC

Rails 3:使用h(即HTML_escape)的助手应该在哪里生存?

  •  1
  • AlexC  · 技术社区  · 14 年前

    我正在用RubyonRails3编写一个webapp。Rails3自动避开任何潜在的坏字符串,这通常是一件好事,但意味着如果您自己组装HTML,则必须调用 html_safe 关于它。

    我有一个卡片模型,它有几个文本字段,其中的内容不可信(可能包含邪恶的HTML或脚本)。我有一个函数,它使用关于特定卡片的其他知识,对其中一个文本字段执行一些转换,以生成HTML输出。我想将这个函数生成的HTML嵌入到应用程序的几个部分的多个地方。

    从概念上讲,这个助手与视图有关。但是,我找不到在视图文件中编写函数的任何方法;似乎它们必须进入帮助程序或控制器/模型中。

    由于此函数非常特定于卡对象,下一个最佳选项是在我的卡模型card.rb中具有函数:

    class Card < ActiveRecord::Base
    [...]
    def format(unsafe_text)
      initial_text = h unsafe_text   # aka html_escape unsafe_text
      # assembles HTML output based on initial_text and fields of self
      output_text.html_safe!
    end
    

    然后,我想在不同的视图中通过执行以下操作来调用它:

    Rules text: <%= format(@card.rulestext) %>
    

    然而,这里也有一个大问题。在card model card.rb中,我可以使用 html_safe! 功能,但我不能使用 h html_escape . 似乎 H 逃逸 函数只在erb视图中可用,而不在助手或控制器中!

    有一些解决办法。我可以做 format 不清理输入,然后离开

    Rules text: <%= format(h(@card.rulestext)) %>
    

    但这两种情况都很容易发生危险的失误(其中一个丢失了 h() 我们有问题),而且非常不干燥。目前我正在使用一个部分来访问 () 功能:

    (in a normal view)
    Rules text: <%= render 'formattext', :text=> @card.rulestext %>
    
    (app/views/shared/_formattext.html.erb)
    <%= @card.format(html_escape(text)) %>
    

    但这仍然很危险。我要做的就是打个电话给 format(sometext) 在一个视图中,而不是调用 render 'formattext', :text=> sometext 我收到了一些没有转载的短信。

    有更好的方法吗?有没有一种方法可以写助手函数来活在视图中而不是模型或控制器中?

    2 回复  |  直到 12 年前
        1
  •  2
  •   Jacob    14 年前

    class CardHelper
      def rules(card)
        initial_text = h card.rules_text
        # assembles HTML output based on initial_text and fields of card
        output_text.html_safe
      end
    end
    

    format

    class CardHelper
      def format(card, attribute)
        initial_text = h card[attribute]
        # assembles HTML output based on initial_text and fields of card
        output_text.html_safe
      end
    end
    

    class CardsController
      helper CardHelper
    end
    

    <%= rules(@card) %>
    

    <%= format(@card, :rules) %>
    
        2
  •  2
  •   Simone Carletti    14 年前

    h

    html_safe!