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

Ruby Rails 3:如何拦截任何http请求,ruby,ruby-on-rails-3.1,rubygems,rake-task,Ruby,Ruby On Rails 3.1,Rubygems,Rake Task,假设我在app/assets/images/privateimages/myrestrictedimage1.jpg上有一张图片 如果我试图通过url直接访问图像,可以说 http://localhost:5555/assets/privateimages/myrestrictedimage1.jpg 我能看到这张照片 我希望有一种方法来检查任何http请求,以确定是否允许用户访问它 我知道在继续执行任何控制器操作之前,我可以使用控制器中的before_filter进行一些预处理,但我认为这

假设我在app/assets/images/privateimages/myrestrictedimage1.jpg上有一张图片 如果我试图通过url直接访问图像,可以说

 http://localhost:5555/assets/privateimages/myrestrictedimage1.jpg
我能看到这张照片

我希望有一种方法来检查任何http请求,以确定是否允许用户访问它

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

我听说我可能可以用一个rake任务来完成它,但经过多次搜索,我还没有找到任何像我尝试做的事情。也许我必须创建一个ruby gem来实现这一点,但我不知道如何实现这一点

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

你想看看(不是rake)。

我用的是Rack中间件

中间件类如下所示:

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执行其他类型的逻辑,然后继续。因此,例如,如果用户转到*则运行对url执行检查的某些代码,如果检查通过,则用户可以继续转到/*正常情况下,否则他们将重定向到其他url。请更新您的答案,因为中间件名称不能再用引号书写。它将在Rails版本5中抛出一个错误。