Skip to content

Commit f8f50fc

Browse files
committed
Add new scrubber suitable for strip tags but adding whitespace
1 parent a105af7 commit f8f50fc

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

lib/rails/html/scrubbers.rb

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

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)