路由机架问题
我正在使用Ruby on Rails 3,我想将一些URL路由到一些Rack中间件。 也就是说,如果用户尝试浏览http://.com/api/user/1
,系统应考虑在Rack文件之前运行,然后继续执行请求。
我有一个Rack :: Api:用户位于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
但没有人工作。
UPDATE
我的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
在启动过程中的某个地方使用你的Rack应用程序,比如在初始化程序中(请记住,除非你编写代码,否则不会自动加载来自lib
文件!请参阅此SO答案以获取更多信息 ),然后尝试不加引号安装它。 例如,而不是:
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
是加载和插入中间件的文件。 希望这是你正在寻找的!