Skip to content

Commit

Permalink
SGML#to_proc (#775)
Browse files Browse the repository at this point in the history
Experimenting with a `to_proc` interface on SGML components.
  • Loading branch information
joeldrapper authored Sep 9, 2024
1 parent cd11602 commit cd1234b
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 20 deletions.
29 changes: 9 additions & 20 deletions lib/phlex/sgml.rb
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,10 @@ def await(task)
end
end

def to_proc
proc { |c| c.render(self) }
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, fragments: nil, &block)
@_buffer = buffer
Expand Down Expand Up @@ -243,9 +247,6 @@ def safe(value)

alias_method :🦺, :safe

private

# @api private
def flush
return if @_context.capturing

Expand All @@ -254,23 +255,7 @@ def flush
buffer.clear
end

# Render another component, block or enumerable
# @return [nil]
# @overload render(component, &block)
# Renders the component.
# @param component [Phlex::SGML]
# @overload render(component_class, &block)
# Renders a new instance of the component class. This is useful for component classes that take no arguments.
# @param component_class [Class<Phlex::SGML>]
# @overload render(proc)
# Renders the proc with {#yield_content}.
# @param proc [Proc]
# @overload render(enumerable)
# Renders each item of the enumerable.
# @param enumerable [Enumerable]
# @example
# render @items
def render(renderable, &)
def render(renderable = nil, &)
case renderable
when Phlex::SGML
renderable.call(@_buffer, context: @_context, view_context: @_view_context, parent: self, &)
Expand All @@ -288,13 +273,17 @@ def render(renderable, &)
end
when String
plain(renderable)
when nil
yield_content(&) if block_given?
else
raise Phlex::ArgumentError.new("You can't render a #{renderable.inspect}.")
end

nil
end

private

# Like {#capture} but the output is vanished into a BlackHole buffer.
# Because the BlackHole does nothing with the output, this should be faster.
# @return [nil]
Expand Down
29 changes: 29 additions & 0 deletions quickdraw/sgml/to_proc.test.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# frozen_string_literal: true

class App < Phlex::HTML
def view_template
render Example do |e|
e.slot(&Sub.new)
end
end
end

class Example < Phlex::HTML
def view_template(&)
article(&)
end

def slot(&)
render(&)
end
end

class Sub < Phlex::HTML
def view_template
h1 { "Sub" }
end
end

test do
expect(App.new.call) == "<article><h1>Sub</h1></article>"
end

0 comments on commit cd1234b

Please sign in to comment.