Sinatra render a ruby file
How to render a ruby file (which in my case returns a pdf document) for example:
get "/pdf" do
@locals = {some_locals_hash}
headers({'Content-Type' => 'application/pdf',
'Content-Description' => 'File Transfer',
'Content-Transfer-Encoding' => 'binary',
'Content-Disposition' => "attachment;filename=\"test.pdf\"",
'Expires' => '0',
'Pragma' => 'public'})
ruby :test, :layout => false, :locals => @locals
end
I know Tilt does not have ruby template. For now I put all content in a *.haml
file like:
-# PDF file description
:ruby
pdf = Prawn::Do开发者_如何学运维cument.new(
... docs settings)
... docs content
end
= pdf.render()
and I render it with haml :template ...etc...
Truth is, I only need this for syntax highlighting, my editor does not properly highlight embedded ruby code in haml files :(. So if it's to complicated don't bother...
I managed with a Tilt template
module Tilt
class RubyTemplate < Template
def prepare
end
def evaluate(scope, locals, &block)
super(scope, locals, &block)
end
def precompiled_template(locals)
data.to_str
end
end
register 'rb', RubyTemplate
end
and with a helper method
helpers do
def ruby(*args)
render(:rb, *args)
end
end
I't sure this is the best way, but at least is working :)
精彩评论