[英]Ruby on Rails/Rack Builder “Use” Method Wrong Number of Arguments
[英]“use” keyword/word in Ruby/Rails/Rack code
最近我碰巧在Ruby代码中看到了这个词, use
时,我正在浏览一些与goliath ,middleware等相关的代码。看起来它与include
/ extend
和require
有所不同。
有人可以解释为什么这个use
关键字存在,以及它与include
/ require
区别? 它是如何工作的,什么时候使用它?
正如人们所指出的, use
不是Ruby关键字,它实际上是Rack::Builder
类的一种方法:
use(middleware, *args, &block)
指定要在堆栈中使用的中间件。
该文档 ( 由@ user166390指出 )描述如下:
Rack::Builder
实现了一个小型DSL,以迭代方式构建Rack
应用程序。例:
app = Rack::Builder.new { use Rack::CommonLogger use Rack::ShowExceptions map "/lobster" do use Rack::Lint run Rack::Lobster.new end }
要么
app = Rack::Builder.app do use Rack::CommonLogger lambda { |env| [200, {'Content-Type' => 'text/plain'}, 'OK'] } end
use
将中间件添加到堆栈,run
调度到应用程序。
我不是太熟悉的Rack::Builder
的源代码 ,但它看起来每次调用时喜欢use
一个新的中间件模块,它被添加到阵列中,每个模块运行/以相反的顺序注入其中它被添加(后进先出顺序,也就是堆栈顺序)。 运行以前的中间件的结果通过inject
传递到堆栈中的下一个中间件:
第53-56行 :
def initialize(default_app = nil,&block) # @use is parallel assigned to []. @use, @map, @run = [], nil, default_app instance_eval(&block) if block_given? end
第81-87行 :
def use(middleware, *args, &block) if @map mapping, @map = @map, nil @use << proc { |app| generate_map app, mapping } end # The new middleware is added to the @use array. @use << proc { |app| middleware.new(app, *args, &block) } end
131-135行 :
def to_app app = @map ? generate_map(@run, @map) : @run fail "missing run or map statement" unless app # The middlewares are injected in reverse order. @use.reverse.inject(app) { |a,e| e[a] } end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.