-
-
Notifications
You must be signed in to change notification settings - Fork 39
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Co-authored-by: Will Cosgrove <[email protected]>
- Loading branch information
1 parent
e15f760
commit f6b2e03
Showing
3 changed files
with
66 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
# frozen_string_literal: true | ||
|
||
module Phlex::Rails::FragmentFinder | ||
extend self | ||
|
||
Parser = if defined?(Nokolexbor) | ||
Nokolexbor | ||
else | ||
require "nokogiri" | ||
Nokogiri::HTML | ||
end | ||
|
||
def extract(html, ids) | ||
parsed = Parser.parse(html) | ||
selector = ids.map { |id| "##{id}" }.join(", ") | ||
|
||
result = +"" | ||
|
||
ids.count.times do | ||
if (fragment = parsed.at_css(selector)) | ||
result << fragment.to_s | ||
fragment.remove | ||
end | ||
end | ||
|
||
result | ||
end | ||
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,37 @@ | ||
# frozen_string_literal: true | ||
|
||
describe Phlex::Rails::FragmentFinder do | ||
include Phlex::Rails::FragmentFinder | ||
it "find one" do | ||
expect( | ||
extract(<<~HTML, ["b"]) | ||
<div id="a">A</div> | ||
<div id="b">B</div> | ||
<div id="c">c</div> | ||
HTML | ||
).to be == %(<div id="b">B</div>) | ||
end | ||
|
||
it "find two" do | ||
expect( | ||
extract(<<~HTML, ["b", "c"]) | ||
<div id="a">A</div> | ||
<div id="b">B</div> | ||
<div id="c">C</div> | ||
<div id="d">D</div> | ||
HTML | ||
).to be == %(<div id="b">B</div><div id="c">C</div>) | ||
end | ||
|
||
it "doesn't duplicate" do | ||
expect( | ||
extract(<<~HTML, ["b", "c"]) | ||
<div id="a">A</div> | ||
<div id="b">B | ||
<div id="c">C</div> | ||
</div> | ||
<div id="d">D</div> | ||
HTML | ||
).to be == %(<div id="b">B\n\t<div id="c">C</div>\n</div>) | ||
end | ||
end |