Skip to content

Instantly share code, notes, and snippets.

@seaofclouds
Forked from rtomayko/staticizer.rb
Created March 14, 2009 02:49
Show Gist options
  • Save seaofclouds/78895 to your computer and use it in GitHub Desktop.
Save seaofclouds/78895 to your computer and use it in GitHub Desktop.
add static file export to sinatra apps!
# http://groups.google.com/group/sinatrarb/browse_thread/thread/84d525759af8615a
require 'fileutils'
class Staticizer
def initialize(app, cache_path)
@app = app
@cache_path = cache_path
end
def call(env)
status, headers, body = @app.call(env)
if status == 200
filename = File.join(@cache_path, env['PATH_INFO'])
filename += 'index' if filename =~ /\/$/
filename += '.html' unless filename =~ /\.\w+$/
dirname = File.dirname(filename)
FileUtils.mkdir_p dirname
File.open(filename, 'wb') do |io|
body.each { |part| io.write(part) }
end
body = File.open(filename, 'rb')
end
[status, headers, body]
end
end
require 'rubygems'
require 'sinatra'
require 'staticizer'
use Staticizer, "./static"
get '/' do
'<html>BAM!</html>'
# staticizer will output /index.html PERFECT!
end
get '/foo/bar' do
"Hello World!"
# staticizer outputs /foo/bar.html CLOSE...
# instead, can we make it output /foo/bar/index.html
# that way we preserve the url structure for easy linkage in views
end
get '/bling/' do
"Oh, nice"
# staticizer outputs /bling.html preferred would be /bling/index.html
end
get '/something.xml' do
"<foo><bar/></foo>"
# staticizer outputs something.xml PERFECT
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment