开发者

Trouble on routing Racks

开发者 https://www.devze.com 2023-02-13 06:34 出处:网络
I am using Ruby on Rails 3 and I would like to route some URLs to some Rack middlewares. That is, if a user try to browse at http://<my_site_name>.com/api/user/1 the system should consider to ru

I am using Ruby on Rails 3 and I would like to route some URLs to some Rack middlewares. That is, if a user try to browse at http://<my_site_name>.com/api/user/1 the system should consider to run before a Rack file and then proceed in the request.

I have a Rack::Api:User located in the lib/rack/api/user folder.

From the RoR official documentation I discovered this:

     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.

In the routers.rb file I 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

I also 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

but no one works.


UPDATE

My Rack file is something like this:

  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


Assuming you're require-ing your Rack app somewhere in your bootup process, like in an initializer (keep in mind that files from lib are not automatically loaded anymore unless you write code to do so! see this SO answer for more), then try mounting it without quotes. For example, instead of:

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

try

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

[Update]

Here is a link to the changes I made to a basic Rails application that demonstrates both autoloading and mounting a Rack application: https://github.com/BinaryMuse/so_5100999/compare/master...rack

[Update 2]

Ah, I see what you're saying now. You want a middleware. I've updated the code at the above URL to implement your application as middleware. config/initializers/rack.rb is the file that loads and inserts the middleware. Hope this is what you're looking for!

0

精彩评论

暂无评论...
验证码 换一张
取 消