Skip to content

Instantly share code, notes, and snippets.

@rafael
Created October 29, 2013 22:01
Show Gist options
  • Select an option

  • Save rafael/7223432 to your computer and use it in GitHub Desktop.

Select an option

Save rafael/7223432 to your computer and use it in GitHub Desktop.
require 'rack/utils'
class StaticFileServer
def initialize
@middleware_stack = ActionDispatch::MiddlewareStack.new
@middleware_stack.use ActionDispatch::ShowExceptions, show_exception_app unless Rails.env.development?
@middleware_stack.use Bugsnag::Rack
end
def call(env)
@app = build_app
@app.call(env)
end
private
def build_app
@app ||= @middleware_stack.build(Base.new)
end
def show_exception_app
ActionDispatch::PublicExceptions.new(Rails.public_path)
end
class Base
def call(env)
path = env["SERVER_NAME"]
raise StandardError.exception("This is a test")
file, headers = pick_file_and_headers_for_path(path, env)
::Rack::File.new(file, headers).call(env)
end
private
def get_best_encoding(request)
Rack::Utils.select_best_encoding(%w(gzip identity), request.accept_encoding)
end
def headers
@headers ||= {'Content-Type' => 'text/html' }
end
def pick_file_and_headers_for_path(path, env)
request = Rack::Request.new(env)
encoding = get_best_encoding(request)
file = "#{Rails.root.to_s}/public/media_kits/" + path + '.html'
if File.exist?(file)
if encoding == 'gzip'
file = file + '.gz'
headers['Content-Encoding'] = 'gzip'
end
else
raise ActionController::RoutingError.exception("Page Not Found")
end
[file, headers]
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment