Rails 3:如何拦截任何http请求

让我说我在app / assets / images / privateimages / myrestrictedimage1.jpg有一个图像如果我试图通过url直接转到图像说像

http://localhost:5555/assets/privateimages/myrestrictedimage1.jpg 

我能够查看图像。

我想有办法检查任何http请求,以决定是否允许用户访问它。

我知道我可以在控制器中使用before_filter进行一些预处理,然后继续执行任何控制器操作,但我不认为这会对我有所帮助,因为我需要尝试执行控制器操作才能使其生效。

我听说我可以用rake任务做到这一点但经过多次搜索后我找不到任何类似于我想做的事情。 也许我必须创建一个ruby gem才能做到这一点,但我不知道如何做到这一点。

谁能指出我正确的方向? 谢谢。

我用过Rack Middleware

中间件类看起来像这样:

 class MyChecker def initialize(app) @app = app end def call(env) if (docheck) #do stuff here such as check the path. #For example @path = env['PATH_INFO'] and compare against your okay paths #if youre good and are able to continue then @app.call(env) else #redirect such as [301, {"Location" => /somewhere, "Content-Type" => "text/html"}, []] end end end 

确保通过将以下内容添加到application.rb来使您的中间件可见

 class Application < Rails::Application ... config.autoload_paths += %W(#{config.root}/lib) #if MyChecker is located in lib othewise substitute lib with wherever you have your middleware class config.middleware.use "MyChecker" end 

你想看看Rack (不是rake)。