Last active
December 26, 2015 19:19
-
-
Save rafael/7200495 to your computer and use it in GitHub Desktop.
Rack to serve statics files with a middleware
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| require 'rack/utils' | |
| module Openair | |
| class MediaKitStaticRack | |
| def initialize | |
| @middlewares = [:bugsnag] | |
| @middlewares << :errors unless Rails.env.development? | |
| end | |
| def call(env) | |
| @app = load_app | |
| @app.call(env) | |
| end | |
| private | |
| def load_app | |
| @app ||= @middlewares.reduce(Base.new) do |app, middleware| | |
| app = self.send("initialize_middleware_#{middleware}", app) | |
| end | |
| end | |
| def initialize_middleware_bugsnag(app) | |
| Bugsnag::Rack.new(app) | |
| end | |
| def initialize_middleware_errors(app) | |
| ActionDispatch::ShowExceptions.new(app, | |
| ActionDispatch::PublicExceptions.new("#{Rails.root}/public")) | |
| end | |
| class Base | |
| def call(env) | |
| path = env["SERVER_NAME"] | |
| 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 | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment