Skip to content

Instantly share code, notes, and snippets.

@dira
Created November 10, 2009 19:55
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dira/231212 to your computer and use it in GitHub Desktop.
Save dira/231212 to your computer and use it in GitHub Desktop.
# see http://coderack.org/users/dira/middlewares/76-haml-sass-for-static-sites
app = Rack::Builder.new do
use Rack::SiteGenerator#, :generators => { :html => :erb, :css => :less }, :source_path => "views/others"
run Rack::StaticApp.new
end
Rack::Handler::Mongrel.run app, :Port => 9292
module Rack
class SiteGenerator
require 'fileutils'
GENERATORS = {
:haml => ["haml", "haml %s %s"],
:erb => ["erb" , "erb %s > %s"],
:less => ["less", "lessc %s %s"],
:sass => ["sass", "sass %s %s"]
}
def initialize(app, options = {})
@app = app
@generators = options[:generators] || { :html => :haml, :css => :sass }
@source_path = options[:source_path] || 'views'
end
def call(env)
path = env["REQUEST_PATH"]
extension = ::File.extname(path)[1..-1]
generator = GENERATORS[@generators[extension.to_sym]] rescue nil
if generator
source = path.gsub(/^\//, "#{@source_path}/")
source.gsub!(/\.#{extension}$/, ".#{generator[0]}")
destination = "public#{path}"
::FileUtils.mkdir_p(::File.dirname(destination))
`#{generator[1] % [source, destination]}` unless valid?(source, destination)
end
@app.call(env)
end
def valid?(source, generated)
::File.exist?(generated) && ::File.mtime(generated) > ::File.mtime(source)
end
end
end
module Rack
class StaticApp
def call(env)
path = env["REQUEST_PATH"]
file_path = ::File.join(::File.dirname(__FILE__), "public", path)
::File.exist?(file_path) ?
[200, {}, ::File.new(file_path, "r")] :
[404, {}, ""]
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment