我正在使用Ruby on Rails 3,我想將一些URL路由到某些Rack中間件。也就是說,如果用戶嘗試瀏覽http://<my_site_name>.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文件我tryed
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
我也tryed
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
但沒有人KS。
UPDATE
我機架文件是這樣的:
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
你能舉一個真實的例子嗎?如果我的機架文件位於'/ lib/api/user /'中,我該如何以及在哪裏必須'需要'那個? P.S .:我寫了代碼在'application.rb'文件('config.autoload_paths + =%W(#{config.root}/lib)')中加載'lib'路徑。附:二:我更新了這個問題。 P.S .:我嘗試了你的代碼,但是我得到了同樣的錯誤。 – user502052 2011-02-24 20:06:20
如果我沒有弄錯,如果你想自動加載Rack :: Api :: User,那麼這個類應該在'lib/rack/api/user.rb'中定義。無論如何,你可以通過在'config/initializers/load_my_rack_app.rb'中創建一個文件來手動加載文件(自動加載'config/initializers'中的任何東西),並將代碼放在'require'lib/api/user/whatever.rb「'。 – 2011-02-24 20:22:37
但我得到'失蹤:控制器'。那是'user.rb'文件中的機架語句嗎? – user502052 2011-02-24 22:03:26