Skip to content

Commit

Permalink
Add SGML#each to support the Rack interface
Browse files Browse the repository at this point in the history
  • Loading branch information
joeldrapper committed Oct 4, 2023
1 parent 9e5820d commit 5a0bca2
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
7 changes: 7 additions & 0 deletions lib/phlex/sgml.rb
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,13 @@ def await(task)
end
end

# Yields each fragment of the view to the given block, which is useful for streaming.
def each(&block)
enumerator = Enumerator.new { |e| call(e) }

block ? enumerator.each(&block) : enumerator
end

# Renders the view and returns the buffer. The default buffer is a mutable String.
def call(buffer = +"", context: Phlex::Context.new, view_context: nil, parent: nil, &block)
__final_call__(buffer, context: context, view_context: view_context, parent: parent, &block).tap do
Expand Down
26 changes: 26 additions & 0 deletions test/phlex/view/each.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# frozen_string_literal: true

class Example < Phlex::HTML
def template
h1 { "Hello, world!" }
end
end

describe "#each" do
it "returns an enumerator" do
expect(Example.new.each).to be_a Enumerator
expect(Example.new.each.to_a).to be == ([%(<h1>Hello, world!</h1>)])
end

with "block" do
it "yields each fragment to the block" do
fragments = []

Example.new.each do |fragment|
fragments << fragment
end

expect(fragments).to be == ([%(<h1>Hello, world!</h1>)])
end
end
end

0 comments on commit 5a0bca2

Please sign in to comment.