Skip to content

Instantly share code, notes, and snippets.

@Aupajo
Created August 27, 2013 03:22
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Aupajo/6349315 to your computer and use it in GitHub Desktop.
Save Aupajo/6349315 to your computer and use it in GitHub Desktop.
Rack app for serving pre-generated GZip responses
class StaticGZip
DIRECTORY_INDEX = "index.html"
attr_accessor :root_dir
def initialize(root_dir)
@root_dir = root_dir
end
def call(env)
request = Rack::Request.new(env)
file_path = File.join(File.dirname(__FILE__), root_dir, request.path)
static_file = StaticFile.locate(file_path)
static_file.to_response
end
class StaticFile
attr_accessor :body
def initialize(body)
@body = body
end
def code
200
end
def headers
{}
end
def to_response
[code, headers, [body]]
end
def self.locate(path)
file_path = path.sub(/\/$/, "/#{DIRECTORY_INDEX}")
[GZipFile, StaticFile, NullFile].each do |klass|
file = klass.from_path(file_path)
return file unless file.nil?
end
end
def self.from_path(path)
return unless File.exists?(path)
body = File.read(path)
self.new(body)
end
end
class GZipFile < StaticFile
def headers
{ 'Content-Encoding' => 'gzip' }
end
def self.from_path(path)
super "#{path}.gz"
end
end
class NullFile < StaticFile
def initialize
end
def code
404
end
def body
"Not found"
end
def self.from_path(path)
self.new
end
end
end
run StaticGZip.new("build")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment