seaofclouds (owner)

Fork Of

Revisions

gist: 78895 Download_button fork
public
Description:
add static file export to sinatra apps!
Public Clone URL: git://gist.github.com/78895.git
Embed All Files: show embed
staticizer.rb #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# 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
yourapp.rb #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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