Skip to content

Instantly share code, notes, and snippets.

@fauxparse
Created July 16, 2009 22:01
Show Gist options
  • Save fauxparse/148718 to your computer and use it in GitHub Desktop.
Save fauxparse/148718 to your computer and use it in GitHub Desktop.
# Allow the metal piece to run in isolation
require(File.dirname(__FILE__) + "/../../config/environment") unless defined?(Rails)
# Speeds up the presentation of static files by not going through Rails at all.
# TODO: streaming for large files
class StaticFiles
MAX_FILE_SIZE = 262_144 # 256KB
def self.call(env)
static_file_name = File.join Rails.root, "assets", env["SERVER_NAME"], "original", env["PATH_INFO"]
if env["PATH_INFO"] != "/" && File.exist?(static_file_name) && File.size(static_file_name) < MAX_FILE_SIZE
content_type = File.mime_type?(static_file_name)
if Rails.env == "production"
[200, {
"Content-Type" => content_type,
"Expires" => (Time.now + 1.week).to_s(:rfc822),
"Cache-Control" => "max-age=#{1.week.to_i}",
"X-Sendfile" => static_file_name
}, [""]]
else
file = File.open(static_file_name)
contents = file.read
file.close
[200, {
"Content-Type" => content_type,
"Expires" => (Time.now + 1.week).to_s(:rfc822),
"Cache-Control" => "max-age=#{1.week.to_i}"
}, [contents]]
end
else
[404, {"Content-Type" => "text/html"}, ["Not Found"]]
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment