What is the third argument to config.middleware.insert_before?

1.9k views Asked by At

I have been using the following in config/environments/staging.rb to keep my staging environment private:

# HTTP Basic Authentication
if ENV['AUTH_BASIC_ON'] == 'true'
  config.middleware.insert_before(ActionDispatch::Static, 'Rack::Auth::Basic', 'Staging') do |username, password|
    [username, password] == [ENV.fetch('AUTH_BASIC_USERNAME'), ENV.fetch('AUTH_BASIC_PASSWORD')]
  end
end

What is config.middleware.insert_before's third argument ('Staging')? What implication does this particular parameter bear? If I want to run this code in production (by copy/pasting it into config/environments/production.rb), should I change this parameter to 'Production'? What if I change it to 'Fubar'?

I tried looking this up in the docs and source code, but it is unexplained. Also, I found it mentioned in a book, but the explanation is weak at best:

The args parameter is an optional hash of attributes to pass to the initializer method of your Rack filter.

2

There are 2 answers

0
Ju Liu On

It's simply the message sent to the browser by the Rack::Auth::Basic middleware; look at the screenshot below :)

enter image description here

0
agbodike On

More general detail regarding the args:

As stated in the docs, they are an array passed to the initializer of the middleware or filter, but whether there should be any args, and the meaning of them, is dependent upon the the code being called.

A simple contrived example is a middleware for debugging a Rails app:

class MiddlewareDebugger
  def initialize(app, *args)
    @app = app
    @args = args
  end

  def call(env)
    Rails.logger.debug "MiddlewareDebugger #{@args.first}"
    status, headers, body = @app.call(env)
    [status, headers, body]
  end
end

and in config/application.rb I might add

config.middleware.insert_before Rack::Head, "MiddlewareDebugger", "1"
config.middleware.insert_before Rack::ConditionalGet, "MiddlewareDebugger", "2"

It would log the string MiddlewareDebugger 1 before Rack::Head and MiddlewareDebugger 2 before Rack::ConditionalGet