如何在Ruby中编码/解码HTML实体?
我正在尝试解码一些HTML实体,比如'&lt;' 成为'<' 。 
我有一个老的gem( html_helpers ),但似乎已经被遗弃了两次。
任何build议? 我将需要在模型中使用它。
HTMLEntities可以做到这一点:
 : jmglov@laurana; sudo gem install htmlentities Successfully installed htmlentities-4.2.4 : jmglov@laurana; irb irb(main):001:0> require 'htmlentities' => [] irb(main):002:0> HTMLEntities.new.decode "¡I'm highly annoyed with character references!" => "¡I'm highly annoyed with character references!" 
 要对字符进行编码,您可以使用CGI.escapeHTML : 
 string = CGI.escapeHTML('test "escaping" <characters>') 
 为了解码他们,有CGI.unescapeHTML : 
 CGI.unescapeHTML("test "unescaping" <characters>") 
当然,在这之前你需要包含CGI库:
 require 'cgi' 
 如果你在Rails中,你不需要使用CGI来编码string。 有h方法。 
 <%= h 'escaping <html>' %> 
要在Rails中解码字符,请使用:
 <%= raw '<html>' %> 
所以,
 <%= raw '<br>' %> 
会输出
 <br> 
我觉得Nokogirigem也是不错的select。 这是非常稳定的,有一个巨大的贡献社区。
样品:
 a = Nokogiri::HTML.parse "foo bär" a.text => "foo bär" 
要么
 a = Nokogiri::HTML.parse "¡I'm highly annoyed with character references!" a.text => "¡I'm highly annoyed with character references!" 
 如果你不想添加一个新的依赖(就像HTMLEntities ),并且你已经使用了Hpricot ,那么它就可以为你逃跑和逃避。 它比CGI处理更多: 
 Hpricot.uxs "foo bär" => "foo bär" 
 你可以使用htmlasciigem: 
 Htmlascii.convert string 
 <% str="<h1> Test </h1>" %> result: < h1 > Test < /h1 > <%= CGI.unescapeHTML(str).html_safe %>