Sinatra - 类似控制器的设置,具有自动加载/包含功能?

发布于 2024-12-12 05:11:06 字数 225 浏览 6 评论 0原文

我喜欢 Rails 将每个控制器放在自己的文件中,并且自动加载,我正在尝试为我的 Sinatra 站点做同样的事情。

例如,我有我的“用户”页面,即 users/loginusers/logout 等,我想做的就是将所有这些分开,以及其他页面,如新闻、admincp 等到它们自己的文件中。

当我的 Sinatra 网站启动时,我该如何自动加载它们?

I like how Rails has each controller in it's own file and it's automatically loaded and I'm trying to do the same for my Sinatra site.

I have, for example, my "Users" pages, which is users/login, users/logout and so on, what I'd like to do is seperate all these, and other pages, like news, admincp, and so on into their own files.

How would I go about having them auto loaded when my Sinatra site is started?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

゛清羽墨安 2024-12-19 05:11:06

这就是我通过我的项目实现这一目标的方法。

我将所有“控制器”放在一个目录中,然后使用以下代码创建了一个名为 init.rb 的文件:

Dir.glob(File.dirname(__FILE__) + '/*.rb').each do |controller|
 require(controller)
end

然后在我的主应用程序文件中添加以下代码:

__DIR__ = ::File.dirname(__FILE__)
require __DIR__ + '/controllers/init'

希望这会有所帮助。

This is how I accomplished this with my project.

I put all the "controllers" in a directory, I then created a file named init.rb with the following code:

Dir.glob(File.dirname(__FILE__) + '/*.rb').each do |controller|
 require(controller)
end

Then in my main app file the following code:

__DIR__ = ::File.dirname(__FILE__)
require __DIR__ + '/controllers/init'

Hope this helps.

指尖凝香 2024-12-19 05:11:06

如果你想要更多的 gem,你可以使用超小的 require_all。那么它就会像这样简单:

require_all 'controllers/init'

眼睛更容易看到,但另一方面又增加了依赖性。

If you want to have more gems you can use the super tiny require_all. It would then be as easy as:

require_all 'controllers/init'

A lot easier on the eye but on the other hand an added dependency.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文