ruby-on-rails – 特定Rails路由上的Trigger Rack中间件

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – 特定Rails路由上的Trigger Rack中间件前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
是否可以仅在特定的Rails路由上触发Rack中间件?

例如,假设我想仅在api命名空间上运行速率限制器中间件.

namespace :api do
  resources :users
end

解决方法

我在 Rack::Throttle的速率限制方面取得了很大的成功.子类一个内置的油门类和重载允许的?方法.您的自定义逻辑可以检查正在访问的控制器,并根据需要应用速率限制.
class ApiThrottle < Rack::Throttle::Hourly
  ##
  # Returns `false` if the rate limit has been exceeded for the given
  # `request`,or `true` otherwise.
  #
  # Rate limits are only imposed on the "api" controller
  #
  # @param  [Rack::Request] request
  # @return [Boolean]
  def allowed?(request)
    path_info = (Rails.application.routes.recognize_path request.url rescue {}) || {} 

    # Check if this route should be rate-limited
    if path_info[:controller] == "api"
      super
    else
      # other routes are not throttled,so we allow them
      true
    end
  end
end
原文链接:https://www.f2er.com/ruby/274268.html

猜你在找的Ruby相关文章