Skip to content

Instantly share code, notes, and snippets.

@tomlea
Created June 17, 2009 01:11
Show Gist options
  • Select an option

  • Save tomlea/131017 to your computer and use it in GitHub Desktop.

Select an option

Save tomlea/131017 to your computer and use it in GitHub Desktop.
# Example Rails Usage:
# config.middleware.use Rack::LessCss, "/stylesheets", File.join(RAILS_ROOT, "public", "stylesheets")
#
# public/stylesheets/foo.less is now used to render /stylesheets/foo.css
#
require 'less'
module Rack
class LessCss
File = ::File
def initialize(app, css_path, css_dir)
@app, @css_path, @css_dir = app, css_path, css_dir
end
def generate_content_for(request_path)
if request_path =~ %r{^#{@css_path.chomp("/")}/(.+)\.css$}
if File.exists?(path = File.join(@css_dir, "#{$1}.css"))
File.read(path)
elsif File.exists?(path = File.join(@css_dir, "#{$1}.less"))
Less::Engine.new(File.read(path)).to_css
end
end
end
def call(env)
begin
rv = generate_content_for(env["REQUEST_URI"] || env["PATH_INFO"])
rescue => e
return [500, {"Content-Type" => "text/plain"}, [e.class.name, e.message, e.backtrace.join("\n")]]
end
if rv
[200, {"Content-Type" => "text/css", "Cache-Control" => "max-age=3600, public"}, [rv]]
else
@app.call(env)
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment