This question is about rails source code.
I notice middleware method definded in railties/lib/rails/commands/server.rb ( Rails )
def middleware
middlewares = []
middlewares << [Rails::Rack::Debugger] if options[:debugger]
middlewares << [::Rack::ContentLength]
Hash.new(middlewares)
end
I think it returns a blank hash {} . It overrides the method with same name which definded in lib/rack/server.rb
If I traced right, this method called by build_app which definded in lib/rack/server.rb ( Rack )
def build_app(app)
middleware[options[:environment]].reverse_each do |middleware|
middleware = middleware.call(self) if middleware.respond_to?(:call)
next unless middleware
klass, *args = middleware
app = klass.new(app, *args)
end
app
end
My question is: How does the middleware method works?
The method does not just return a blank hash, despite appearances. The Hash.new
constructor takes the argument and makes that the default value returned if the specified key is missing. Example:
h=Hash.new([1])
h[:missing_key]
=> [1]
The build_app
method is calling middleware[options[:environment]]
. so if the specified environment doesn't exist, it will at least get back a minimal set of middleware.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.