Skip to content

Instantly share code, notes, and snippets.

@rafaelcgo
Last active August 29, 2015 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rafaelcgo/839cc7966972753f6e97 to your computer and use it in GitHub Desktop.
Save rafaelcgo/839cc7966972753f6e97 to your computer and use it in GitHub Desktop.
Offline template renderer to use with rake tasks (or any background worker)
class OfflineTemplate < AbstractController::Base
include AbstractController::Logger
include AbstractController::Rendering
include AbstractController::Layouts
include AbstractController::Helpers
include AbstractController::Translation
include AbstractController::AssetPaths
include ActionDispatch::Routing::UrlFor
include Rails.application.routes.url_helpers
Rails.application.routes.default_url_options = { :host => 'www.yoursite.com' }
helper ApplicationHelper
helper_method :protect_against_forgery?
# configure the different paths correctly
def initialize(*args)
super()
lookup_context.view_paths = Rails.root.join('app', 'views')
config.javascripts_dir = Rails.root.join('public', 'javascripts')
config.stylesheets_dir = Rails.root.join('public', 'stylesheets')
config.assets_dir = Rails.root.join('public')
end
# we are not in a browser, no need for this
def protect_against_forgery?
false
end
# so that your flash calls still work
def flash
{}
end
def params
{}
end
# same asset host as the controllers
self.asset_host = ActionController::Base.asset_host
end
template = OfflineTemplate.new
pdf_page = template.render_to_string partial: 'partial', layout: "pdf", formats: :html, locals: {:@user => user}
kit = PDFKit.new(pdf_page)
kit.stylesheets << "#{Rails.root}/app/assets/stylesheets/pdf/pdf.css"
pdf = open(kit.to_file(temp_dir + user.id.to_s + '_tmp.pdf'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment