Skip to content

Instantly share code, notes, and snippets.

@ryanb
Created November 27, 2012 21:38
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ryanb/4157256 to your computer and use it in GitHub Desktop.
Save ryanb/4157256 to your computer and use it in GitHub Desktop.
Some rack middleware to add headers to asset pipeline.
class AssetHeaders
def initialize(app)
@app = app
end
def call(env)
request = Rack::Request.new(env)
response = @app.call(env)
if request.path =~ /^\/assets\//
# there maybe a better way to add headers
response[1]["Access-Control-Allow-Origin"] = "*"
end
response
end
end
Railscasts::Application.configure do
config.middleware.use "AssetHeaders"
# ...
end
@TSMMark
Copy link

TSMMark commented Nov 21, 2017

Selenium annoyingly does not supply any header or HTTP status data, so I wrote this middleware to inject an HTML comment containing the HTTP status code for use with Capybara.

module Vydia
  module Middleware
    class InjectHeadersForSelenium

      def initialize(app)
        @app = app
      end

      def call(env)
        @status, @headers, @response = @app.call(env)

        if @headers["Content-Type"] && @headers["Content-Type"].include?("text/html")
          @prepend = "<!-- X-Status-Code=#{@status} -->\n"
          @headers = @headers.merge(
            "Content-Length" => (@headers["Content-Length"].to_i + @prepend.size).to_s
          )
        end

        [@status, @headers, self]
      end

      def each(&block)
        if @prepend
          yield(@prepend)
          @prepend = nil
        end

        @response.each(&block)
      end

    end
  end
end

In tests you can get status the code like so:

def get_http_status
  begin
    page.driver.status_code
  rescue Capybara::NotSupportedByDriverError
    matches = /<!-- X-Status-Code=(\d{3}) -->/.match(page.body)
    matches && matches[1] && matches[1].to_i
  end
end

get_http_status

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment