Skip to content

Commit

Permalink
Don't extract plaintext from script and style tags
Browse files Browse the repository at this point in the history
The content of a `script` or `style` tag shouldn't be included
in the plaintext conversion of a node.
  • Loading branch information
intrip committed Jan 13, 2025
1 parent dcbfe09 commit e9e7a81
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
6 changes: 6 additions & 0 deletions actiontext/lib/action_text/plain_text_conversion.rb
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,17 @@ def plain_text_for_node(node, index = 0)
def plain_text_for_node_children(node)
texts = []
node.children.each_with_index do |child, index|
next if skippable?(child)

texts << plain_text_for_node(child, index)
end
texts.join
end

def skippable?(node)
node.name == "script" || node.name == "style"
end

def plain_text_method_for_node(node)
:"plain_text_for_#{node.name}_node"
end
Expand Down
24 changes: 24 additions & 0 deletions actiontext/test/unit/plain_text_conversion_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,30 @@ class ActionText::PlainTextConversionTest < ActiveSupport::TestCase
)
end

test "script tags are ignored" do
assert_converted_to(
"Hello world!",
<<~HTML
<script type="javascript">
console.log("message");
</script>
<div><strong>Hello </strong>world!</div>
HTML
)
end

test "style tags are ignored" do
assert_converted_to(
"Hello world!",
<<~HTML
<style type="text/css">
body { color: red; }
</style>
<div><strong>Hello </strong>world!</div>
HTML
)
end

private
def assert_converted_to(plain_text, html)
assert_equal plain_text, ActionText::Content.new(html).to_plain_text
Expand Down

0 comments on commit e9e7a81

Please sign in to comment.