Skip to content

Commit

Permalink
Add yield_content
Browse files Browse the repository at this point in the history
  • Loading branch information
bradgessler committed Feb 25, 2024
1 parent 1d3a73f commit d734e5d
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 6 deletions.
21 changes: 18 additions & 3 deletions lib/phlex/pdf.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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
Expand Down
25 changes: 22 additions & 3 deletions spec/phlex/pdf_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -31,21 +41,30 @@ 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
end

RSpec.describe Phlex::PDF do
it "generates a PDF" do
PageComponent.render_file "poof.pdf"
PageComponent.render
end
end

0 comments on commit d734e5d

Please sign in to comment.