[英]how rails override the middleware method defined by rack?
This question is about rails source code. 这个问题是关于Rails源代码的。
I notice middleware method definded in railties/lib/rails/commands/server.rb ( Rails ) 我注意到在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
它会覆盖在lib / rack / server.rb中定义的同名方法
If I traced right, this method called by build_app which definded in lib/rack/server.rb ( Rack ) 如果我跟踪正确,此方法由build_app调用,该方法在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. Hash.new
构造函数接受参数,并确保在缺少指定键的情况下返回默认值。 Example: 例:
h=Hash.new([1])
h[:missing_key]
=> [1]
The build_app
method is calling middleware[options[:environment]]
. build_app
方法正在调用middleware[options[:environment]]
。 so if the specified environment doesn't exist, it will at least get back a minimal set of middleware. 因此,如果指定的环境不存在,则至少将获得最少的中间件集。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.