您将Rack中间件文件和要求放在哪里? [英] Where do you put your Rack middleware files and requires?

查看:137
本文介绍了您将Rack中间件文件和要求放在哪里?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将Rails应用程序中内置的一些逻辑重构为中间件,而我遇到的一个烦恼似乎是缺乏将它们放置在何处的约定.

I'm in the process of refactoring some logic built into a Rails application into middleware, and one annoyance I've run into is a seeming lack of convention for where to put them.

目前,我已经选择了app/middleware,但我可以轻松地将其移至vendor/middlewarevendor/plugins/middleware ...

Currently I've settled on app/middleware but I could just as easily move it to vendor/middleware or maybe vendor/plugins/middleware...

最大的问题是必须要求config/environment.rb

The biggest problem is having to require the individual files at the top of config/environment.rb

require "app/middleware/system_message"
require "app/middleware/rack_backstage"

否则在config.middleware.use行上出现未初始化的常量错误.这可能很快就会变得混乱.我宁愿把它藏在某个地方的初始化器中.

or else I get uninitialized constant errors on the config.middleware.use lines. That could get messy very quickly. I'd rather this was tucked away in an initializer somewhere.

有没有放置这些东西的常规场所?

Is there a conventional place to put this stuff?

我正在寻找的与这个赏金有关的具体答案是:我可以在哪里放置需求行,以使它们不会弄乱environment.rb文件,但仍然可以在config.middleware.use调用之前加载? 我尝试过的一切都会导致未初始化的常量错误.

The specific answer I'm looking for with this bounty is: where can I put the require lines so that they are not cluttering the environment.rb file but still get loaded before the config.middleware.use calls? Everything I have tried leads to uninitialized constant errors.

更新:由于我们正在使用Rails 3.0,因此我将Rails应用程序与其他任何Rack应用程序一样对待.中间件的代码文件位于lib(或Gemfile中列出的gem)中,并且是必需的,并已加载到config.ru中.

Update: Now that we're using Rails 3.0, I treat a Rails app like any other Rack app; code files for middleware go in lib (or a gem listed in Gemfile) and are required and loaded in config.ru.

推荐答案

从Rails 3.2开始,Rack中间件属于app/middleware目录.

As of Rails 3.2, Rack middleware belongs in the app/middleware directory.

它可以直接使用,无需任何明确的require语句.

It works "out-of-the-box" without any explicit require statements.

简单示例:

我正在使用称为 CanonicalHost 的中间件类,该类在 app/middleware/canonical_host.rb 中实现.我在production.rb中添加了以下行(请注意:中间件类是显式给出的,而不是用引号引起来的字符串,它适用于任何特定于环境的配置文件):

I'm using a middleware class called CanonicalHost which is implemented in app/middleware/canonical_host.rb. I've added the following line to production.rb (note that the middleware class is explicitly given, rather than as a quoted string, which works for any environment-specific config files):

config.middleware.use CanonicalHost, "example.com"

如果要将中间件添加到 application.rb ,则需要根据

If you're adding middleware to application.rb, you'll need to include quotes, as per @mltsy's comment.

config.middleware.use "CanonicalHost", "example.com"

这篇关于您将Rack中间件文件和要求放在哪里?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆