Skip to content

Commit c214b28

Browse files
jhottensteinflavorjones
authored andcommitted
Add new scrubber suitable for strip tags but adding whitespace
1 parent b579cce commit c214b28

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

Diff for: lib/rails/html/scrubbers.rb

+28
Original file line numberDiff line numberDiff line change
@@ -195,5 +195,33 @@ def scrub(node)
195195
end
196196
end
197197
end
198+
199+
# === Rails::HTML::SpaceBlockElementScrubber
200+
#
201+
# +Rails::HTML::SpaceBlockElementScrubber+ removes all undisplayable tags and contents.
202+
#
203+
# It preserves text contents and inserts a space around block level elements.
204+
class SpaceBlockElementScrubber < Loofah::Scrubber # :nodoc:
205+
def initialize
206+
@direction = :bottom_up
207+
end
208+
209+
def scrub(node)
210+
if Loofah::Elements::LINEBREAKERS.include?(node.name)
211+
replacement = if Loofah::Elements::INLINE_LINE_BREAK.include?(node.name)
212+
" "
213+
else
214+
" #{node.content} "
215+
end
216+
node.add_next_sibling(Nokogiri::XML::Text.new(replacement, node.document))
217+
node.remove
218+
elsif node.text?
219+
return CONTINUE
220+
else
221+
node.before node.children
222+
node.remove
223+
end
224+
end
225+
end
198226
end
199227
end

Diff for: test/scrubbers_test.rb

+14
Original file line numberDiff line numberDiff line change
@@ -200,6 +200,20 @@ def test_skips_text_nodes
200200
end
201201
end
202202

203+
class SpaceBlockElementScrubberTest < ScrubberTest
204+
def setup
205+
@scrubber = Rails::HTML::SpaceBlockElementScrubber.new
206+
end
207+
208+
def test_removes_all_tags_and_keeps_the_text_content_and_adds_spaces
209+
assert_scrubbed %(<div><h1>A list!</h1><ul><li>An element!</li></ul><script>alert("hi!")</script></div>), " A list! An element! "
210+
end
211+
212+
def test_skips_text_nodes
213+
assert_node_skipped("some text")
214+
end
215+
end
216+
203217
class ReturningStopFromScrubNodeTest < ScrubberTest
204218
class ScrubStopper < Rails::HTML::PermitScrubber
205219
def scrub_node(node)

0 commit comments

Comments
 (0)