Skip to content

Commit

Permalink
Add FragmentFilter (#177)
Browse files Browse the repository at this point in the history
Co-authored-by: Will Cosgrove <[email protected]>
  • Loading branch information
joeldrapper and willcosgrove authored Mar 22, 2024
1 parent e15f760 commit f6b2e03
Show file tree
Hide file tree
Showing 3 changed files with 66 additions and 0 deletions.
1 change: 1 addition & 0 deletions lib/phlex/rails.rb
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ module Rails
autoload :Layout, "phlex/rails/layout"
autoload :SGML, "phlex/rails/sgml"
autoload :UnbufferedOverrides, "phlex/rails/unbuffered_overrides"
autoload :FragmentFinder, "phlex/rails/fragment_finder"
end

CSV.prepend Phlex::Rails::CSV::Overrides
Expand Down
28 changes: 28 additions & 0 deletions lib/phlex/rails/fragment_finder.rb
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
37 changes: 37 additions & 0 deletions spec/fragment_filter_spec.rb
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

0 comments on commit f6b2e03

Please sign in to comment.