Difference between disinfection and strip_tags rails

I don't know exactly the difference between them. I read this

http://api.rubyonrails.org/classes/ActionView/Helpers/SanitizeHelper.html

but don't get the exact difference. Can anyone please tell me the difference?

+3


source to share


2 answers


With sanitize you can allow some HTML tags or class, strip_tags cannot. He does the same. Check the code https://github.com/rails/rails/blob/76a0b1028e312b6c3c00a50b4a09d68c23b5e713/actionview/lib/action_view/helpers/sanitize_helper.rb#L80



+2


source


sanitize

uses a whitelisted disinfectant. strip_tags

separates all tags.

For comparison:

[64] pry(main)> sanitize "hello <h1>h1</h1> <b>b</b>"
=> "hello <h1>h1</h1> <b>b</b>"
[65] pry(main)> strip_tags "hello <h1>h1</h1> <b>b</b>"
=> "hello h1 b"

      

If you don't add any whitelisting, sanitize

allows the following tags by default.

[66] pry(main)> ActionView::Base.white_list_sanitizer.allowed_tags.to_a * ', '
=> "strong, em, b, i, p, code, pre, tt, samp, kbd, var, sub, sup,
dfn, cite, big, small, address, hr, br, div, span, h1, h2, h3,
h4, h5, h6, ul, ol, li, dl, dt, dd, abbr, acronym, a, img,
blockquote, del, ins"

      

If you submit your own white tags, they override the defaults.

[67] pry(main)> sanitize "hello <h1>h1</h1> <b>b</b>", tags: %w(b)
=> "hello h1 <b>b</b>"

      



Another difference between sanitize

and strip_tags

is that it sanitize

removes the content (stuff in between) of some tags, especially the tag <script>

.

For comparison:

[68] pry(main)> sanitize "a<script>alet('foo')</script>"
=> "a"
[69] pry(main)> strip_tags "a<script>alet('foo')</script>"
=> "aalet('foo')"

      

Also, it sanitize

does html-escape for some characters, but strip_tags

it doesn't.

[70] pry(main)> sanitize "< &"
=> "&lt; &"
[71] pry(main)> strip_tags "< &"
=> "< &"

      

They also handle nested tags differently. Compare the following,

[73] pry(main)> sanitize "some<<b>script>alert('hello')<</b>/script>", tags: []
=> "some&lt;script>alert('hello')&lt;/script>"
[74] pry(main)> strip_tags "some<<b>script>alert('hello')<</b>/script>"
=> "somealert('hello')"

      

+3


source







All Articles