繁体   English   中英

在Ruby / Rails / Rack代码中使用“use”关键字/单词

[英]“use” keyword/word in Ruby/Rails/Rack code

最近我碰巧在Ruby代码中看到了这个词, use时,我正在浏览一些与goliath ,middleware等相关的代码。看起来它与include / extendrequire有所不同。

有人可以解释为什么这个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传递到堆栈中的下一个中间件:

  1. 第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 
  2. 第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 
  3. 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 

其他资源

  1. 机架快速入门
  2. Ruby on Rack#2 - 构建器

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM