在 Rails 应用程序中构建 2 个中间件堆栈 [英] Build 2 middleware stacks in Rails app
问题描述
我有一个提供网站和 API 的 Rails 应用.
我不希望某些元素出现在 API 的中间件堆栈中,例如:ActionDispatch::Cookies
、ActionDispatch::Session::CookieStore
或 ActionDispatch::Flash
.
网站的中间件堆栈保持正常.
I have a Rails app provides both website and api.
I don't want some elements appear in API's middleware stack, for example : ActionDispatch::Cookies
, ActionDispatch::Session::CookieStore
or ActionDispatch::Flash
.
Website's middleware stack is remain as normal.
那我怎么能做到呢?谢谢.
So how could I do that? Thanks.
推荐答案
我遇到了完全相同的情况,并且想做同样的事情.到目前为止,我已经能够使用 Rails 引擎来添加缺少某些路由的中间件而没有问题(尽管它不一定在堆栈中的正确顺序",但到目前为止似乎工作正常):
I had exactly the same situation, and wanted to do the same thing. So far I have been able to use a Rails Engine to add middleware that is missing without problems for certain routes (although it is not necessarily in the "right order" in the stack, but so far it seems to be working okay):
application.rb:
# after Bundler.require(...)
require_relative '../lib/engines/website/lib/website'
lib/engines/website/lib/website.rb:
require_relative "website/engine"
module Website; end
lib/engines/website/lib/website/engine.rb:
module Website
class Engine < ::Rails::Engine
middleware.use ActionDispatch::Cookies
middleware.use ActionDispatch::Session::CookieStore
middleware.use ActionDispatch::Flash
end
end
config/routes.rb:
mount Website::Engine => "/website"
(或者你可以挂载在/",但是在这种情况下首先定义您的其他路线)
(or you can mount at "/", but define your other routes first in that case)
网站的所有内容都在引擎目录下的典型目录结构中:
And everything for the website goes in the typical directory structure under the engine directory:
lib
engines
website
app
assets
...
controllers
...
views
...
config
routes.rb
lib
website
website.rb
我还没有走多远,但到目前为止,这对我有用.
I haven't gotten very far yet, but so far this is working for me.
注意:从技术上讲,引擎文件甚至不必是网站目录中的单独文件.如果没有其他特别复杂的东西可以添加到您的 lib 目录中,您可以将它推入 website.rb
并使其成为一个单一文件.我发现的唯一要求是文件 does 必须位于引擎自己命名目录中的 lib
目录中(理论上包含 config/routes.rb
和引擎文件结构的其余部分),因为当应用程序预先加载 Rails::Engine 时,引擎会查找其 lib
目录以找到相邻的 应用、配置、供应商等 急切加载.
Note: Technically, the engine file doesn't even have to be a separate file in the website directory. You could just shove it into website.rb
and make it a one-file-wonder if there's nothing else particularly complicated to add to your lib directory. The only requirement I've found is that the file does have to be in a lib
directory inside the engine's own named directory (theoretically containing config/routes.rb
and the rest of the engine's file structure), because when a Rails::Engine is eager-loaded by the app, the engine looks for its lib
directory to find the adjacent app, config, vendor, etc. to eager-load.
这篇关于在 Rails 应用程序中构建 2 个中间件堆栈的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!