Skip to content

Commit

Permalink
Update raw_html.ex to handle :attributes_as_maps option (#498)
Browse files Browse the repository at this point in the history
* Update raw_html.ex

When parsing using the new option :attributes_as_maps, I got errors when trying to convert back with the raw_html function.  This changes the Map into a list where the error occurs and continues regular processing.

* Update floki_test.exs

Checking for two ways the raw_html could be recombined since maps order is not guaranteed
  • Loading branch information
SupaMic authored Dec 11, 2023
1 parent b4bc625 commit a752506
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 0 deletions.
3 changes: 3 additions & 0 deletions lib/floki/raw_html.ex
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,9 @@ defmodule Floki.RawHTML do
defp map_intersperse([head | rest], separator, mapper),
do: [mapper.(head), separator | map_intersperse(rest, separator, mapper)]

defp map_intersperse(%{} = attrs, separator, mapper),
do: map_intersperse(Map.to_list(attrs), separator, mapper)

defp leftpad(:noop), do: ""
defp leftpad(%{pad: pad, depth: depth}), do: String.duplicate(pad, depth)

Expand Down
17 changes: 17 additions & 0 deletions test/floki_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -530,6 +530,23 @@ defmodule FlokiTest do
"""
end

test "raw_html when :attributes_as_maps options was used to parse (new Floki v0.35.0)" do

Check failure on line 533 in test/floki_test.exs

View workflow job for this annotation

GitHub Actions / Elixir 1.12 / OTP 22.3 with fast_html

test raw_html when :attributes_as_maps options was used to parse (new Floki v0.35.0) (FlokiTest)

Check failure on line 533 in test/floki_test.exs

View workflow job for this annotation

GitHub Actions / Elixir 1.12 / OTP 22.3 with html5ever

test raw_html when :attributes_as_maps options was used to parse (new Floki v0.35.0) (FlokiTest)
html_string =
~s(<div id="content"><p><a href="site" class="bar"><span>lol</span><img src="foo.png"/></a></p><br/></div>)

parsed = Floki.parse_document!(html_string, attributes_as_maps: true)

# no guarantee of attribute order from a map
recombined =
case Floki.raw_html(parsed) do
"<div id=\"content\"><p ><a class=\"bar\" href=\"site\"><span >lol</span><img src=\"foo.png\"/></a></p><br /></div>" -> true
"<div id=\"content\"><p ><a href=\"site\" class=\"bar\"><span >lol</span><img src=\"foo.png\"/></a></p><br /></div>" -> true
_other -> false
end

assert recombined
end

# Floki.find/2 - Classes

test "find elements with a given class" do
Expand Down

0 comments on commit a752506

Please sign in to comment.