Skip to content

Instantly share code, notes, and snippets.

@bradgessler
Last active February 23, 2024 23:44
Show Gist options
  • Save bradgessler/b2349923de8391fb9de53ad6243e3130 to your computer and use it in GitHub Desktop.
Save bradgessler/b2349923de8391fb9de53ad6243e3130 to your computer and use it in GitHub Desktop.
Phlex::PDF
require "bundler/inline"
gemfile do
source "https://rubygems.org"
gem "prawn"
gem "zeitwerk"
gem "matrix"
end
module Phlex
class PDF
include Prawn::View
def call(pdf, &block)
@document = pdf
before_template if respond_to?(:before_template)
view_template(&block)
after_template if respond_to?(:after_template)
end
def render(component, &block)
component.call(@document, &block)
nil
end
def self.pdf(doc = Prawn::Document.new)
new.call(doc)
doc
end
end
end
class ApplicationComponent < Phlex::PDF
def before_template
text "Before #{self.class.name}"
end
def after_template
text "After #{self.class.name}"
end
end
class BoxComponent < ApplicationComponent
def view_template
text "I'm a box"
yield
end
end
class NoticeComponent < ApplicationComponent
def view_template
text "Hello World!"
render BoxComponent.new do
text "Look! I'm a box inside a box!"
end
end
end
NoticeComponent.pdf.render_file "poof.pdf"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment