gpt4 book ai didi

ruby-on-rails - 布线 Rack 的问题

转载 作者:太空宇宙 更新时间:2023-11-03 18:30:24 26 4
gpt4 key购买 nike

我正在使用 Ruby on Rails 3,我想将一些 URL 路由到一些 Rack 中间件。也就是说,如果用户尝试浏览 http://<my_site_name>.com/api/user/1系统应该考虑在 Rack 文件之前运行,然后在请求中继续。

我有一个 Rack::Api:User 位于 lib/rack/api/user文件夹。

从 RoR 官方文档中我发现了这一点:

     Mount a Rack-based application to be used within the application.

mount SomeRackApp, :at => "some_route"

Alternatively:

mount(SomeRackApp => "some_route")

All mounted applications come with routing helpers to access them.
These are named after the class specified, so for the above example
the helper is either +some_rack_app_path+ or +some_rack_app_url+.
To customize this helper's name, use the +:as+ option:

mount(SomeRackApp => "some_route", :as => "exciting")

This will generate the +exciting_path+ and +exciting_url+ helpers
which can be used to navigate to this mounted app.

在我试过的routers.rb文件中

mount "Rack::Api::User", :at => "/api/user/1"
# => ArgumentError missing :action

scope "/api/user/1" do
mount "Rack::Api::User"
end
# => NoMethodError undefined method `find' for "Rack::Api::User

我也试过了

match '/api/user/1' => Rack::Api::User
# => Routing Error No route matches "/api/user/1"

match '/api/user/1', :to => Rack::Api::User
# ArgumentError missing :controller

但没有人工作。


更新

我的 Rack 文件是这样的:

  module Api
class User

def initialize(app)
@app = app
end

def call(env)
if env["PATH_INFO"] =~ /^\/api\/user\/i
...
else
@app.call(env)
end
end
end
end

最佳答案

假设您在启动过程中的某处require-ing 您的 Rack 应用程序,例如在初始化程序中(请记住,lib 中的文件不再自动加载除非你编写代码来这样做!请参阅 this SO answer for more ),然后尝试不带引号安装它。例如,而不是:

mount "Rack::Api::User", :at => "/api/user/1"

尝试

mount Rack::Api::User, :at => "/api/user/1"

[更新]

这是我对基本 Rails 应用程序所做更改的链接,该应用程序演示了自动加载和安装 Rack 应用程序:https://github.com/BinaryMuse/so_5100999/compare/master...rack

[更新 2]

啊,我现在明白你在说什么了。你想要一个中间件。我已经更新了上述 URL 中的代码,以将您的应用程序实现为中间件。 config/initializers/rack.rb 是加载和插入中间件的文件。希望这就是您要找的!

关于ruby-on-rails - 布线 Rack 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5100999/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com