From d734e5d68ad53426799d0c0bd0d24fd56b8dbb81 Mon Sep 17 00:00:00 2001 From: Brad Gessler Date: Sun, 25 Feb 2024 12:39:56 -0800 Subject: [PATCH] Add yield_content --- lib/phlex/pdf.rb | 21 ++++++++++++++++++--- spec/phlex/pdf_spec.rb | 25 ++++++++++++++++++++++--- 2 files changed, 40 insertions(+), 6 deletions(-) diff --git a/lib/phlex/pdf.rb b/lib/phlex/pdf.rb index a62a270..a665b85 100644 --- a/lib/phlex/pdf.rb +++ b/lib/phlex/pdf.rb @@ -13,7 +13,13 @@ class Error < StandardError; end def call(document, &block) @document = document around_template do - view_template(&block) + if block_given? + view_template do + yield_content(&block) + end + else + view_template + end end end @@ -38,12 +44,21 @@ def after_template nil end + def yield_content(&block) + return unless block_given? + yield self + end + def render(renderable, &block) case renderable - when String - @document.text renderable when Phlex::PDF renderable.call(@document, &block) + when String + @document.text renderable + when Class + render(renderable.new, &block) if renderable < Phlex::PDF + when Enumerable + renderable.each { |r| render(r, &block) } else raise ArgumentError, "You can't render a #{renderable.inspect}." end diff --git a/spec/phlex/pdf_spec.rb b/spec/phlex/pdf_spec.rb index e7be840..5f464ba 100644 --- a/spec/phlex/pdf_spec.rb +++ b/spec/phlex/pdf_spec.rb @@ -16,6 +16,16 @@ def after_template end end +class WarningComponent < ApplicationComponent + def initialize(message) + @message = message + end + + def view_template + text @message, color: "FF0000" + end +end + class HeaderComponent < ApplicationComponent def view_template text "Header" @@ -31,14 +41,23 @@ def view_template class BodyComponent < ApplicationComponent def view_template render "Body" + yield if block_given? + end + + def greet(name) + text "Hello #{name}", color: "0000FF" end end class PageComponent < ApplicationComponent def view_template render HeaderComponent.new - render BodyComponent.new do - yield + render [ + WarningComponent.new("Danger!"), + WarningComponent.new("Don't Panic!") + ] + render BodyComponent do |body| + body.greet "Brad" end render FooterComponent.new end @@ -46,6 +65,6 @@ def view_template RSpec.describe Phlex::PDF do it "generates a PDF" do - PageComponent.render_file "poof.pdf" + PageComponent.render end end