サニタイズ

hしか使ったことがなかったんだけど
htmlを表示させたい場合は、sanitizeが便利。

用法

h

全部エスケープ処理。
<%= h "" %>
→"&lt;script&gt;alert('')&lt;/script&gt;"

sanitize

表示するタグや属性をホワイトリストで制御。
<%= sanitize "" %>
ホワイトリストに無いので何も表示されない。
<%= sanitize "aaa" %>
→aaa(※強調表示)
 ホワイトリストにあるので表示される。


デフォルトのホワイトリストはこちら。

require 'action_view'
ActionView::Base.sanitized_allowed_tags.sort
=> ["a", "abbr", "acronym", "address", "b", "big", "blockquote", "br", "cite", "code", "dd", "del", "dfn", "div", "dt", "em", "h1", "h2", "h3", "h4", "h5", "h6", "hr", "i", "img", "ins", "kbd", "li", "ol", "p", "pre", "samp", "small", "span", "strong", "sub", "sup", "tt", "ul", "var"]
ActionView::Base.sanitized_allowed_attributes.sort
=> ["abbr", "alt", "cite", "class", "datetime", "height", "href", "name", "src", "title", "width", "xml:lang"]


ちなみにソースはこの辺。

$ view /opt/local/lib/ruby/gems/1.8/gems/actionpack-2.1.2/lib/action_controller/vendor/html-scanner/html/sanitizer.rb
strip_tags/strip_links/sanitize_css

strip_tagsは全タグを削除、strip_linksはaタグを削除、cssのプロパティをホワイトリストで制御。

sanitize_cssホワイトリスト

ActionView::Base.sanitized_allowed_css_properties.sort
=> ["azimuth", "background-color", "border-bottom-color", "border-collapse", "border-color", "border-left-color", "border-right-color", "border-top-color", "clear", "color", "cursor", "direction", "display", "elevation", "float", "font", "font-family", "font-size", "font-style", "font-variant", "font-weight", "height", "letter-spacing", "line-height", "overflow", "pause", "pause-after", "pause-before", "pitch", "pitch-range", "richness", "speak", "speak-header", "speak-numeral", "speak-punctuation", "speech-rate", "stress", "text-align", "text-decoration", "text-indent", "unicode-bidi", "vertical-align", "voice-family", "volume", "white-space", "width"]