什么是Ruby中的“使用ClassName”(vs include,require,load)

问题描述 投票:0回答:1

use SomeClassName在Ruby中做了什么?

在迁移“平/经典”Sinatra应用程序以便为每个控制器使用单独的类的过程中,我遇到了一个博客条目,在某一点上建议require然后use这些类。

#app.rb a Sinatra classic app that formerly had all the routes in app.rb, now moved to separate controller classes
...
require "./app/controllers/foo_controller.rb"
require "./app/controllers/bar_controller.rb"

use Foo # a class with a set of routes
use Bar # a class with a set of routes
...

我已经设法使用Ruby,Sinatra和Rails相当有效率多年没有use声明,并且在任何谷歌查询中添加use这样的常用词并不会缩小搜索范围。

ruby sinatra
1个回答
4
投票

什么是Ruby中的“使用ClassName”(vs include,require,load)

在红宝石中,这意味着什么。它是sinatra API的一部分。

如果这些控制器文件仍包含“经典应用程序”样式代码,则不需要在此处使用use。只需要它们就可以了。

但由于它们现在在技术上是独立的Sinatra应用程序(据我猜测文件的内容),您需要将它们安装在主应用程序中。这是通过将应用程序(及其路由器)注册为中间件来完成的。

这是有问题的方法:https://github.com/sinatra/sinatra/blob/6f15fba2790ebdf4d1215cebf425dea2ea3130ea/lib/sinatra/base.rb#L1430-L1433

© www.soinside.com 2019 - 2024. All rights reserved.