Skip to content

Instantly share code, notes, and snippets.

@henrik
Created May 6, 2013 07:14
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save henrik/5523767 to your computer and use it in GitHub Desktop.
Save henrik/5523767 to your computer and use it in GitHub Desktop.
Small library on top of wkthmltopdf + pdfkit (https://github.com/pdfkit/pdfkit) so e.g. app/models/foo_document.rb can render from app/views/documents/foo_document.html.slim and use partials etc.
class BaseDocument
pattr_initialize :data
def to_pdf
PDFKit.new(to_html).to_pdf
end
def to_html
BaseDocument::TemplateRenderer.new(
template_name, data
).to_html
end
private
# E.g. TestDocument -> test_document.
def template_name
self.class.name.underscore
end
end
class BaseDocument
class TemplateRenderer < AbstractController::Base
include AbstractController::Rendering
self.view_paths = "app/views/documents"
pattr_initialize :template_name, :data
# E.g. `render "my_partial"` will look for
# "#{view_paths}/#{controller_path}/my_partial".
def controller_path
template_name
end
def to_html
render template: template_name, locals: data
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment