Ruby on rails 如何在rails中为特定URL设置超时

Ruby on rails 如何在rails中为特定URL设置超时,ruby-on-rails,timeout,rack,Ruby On Rails,Timeout,Rack,我使用机架超时,工作正常。 但我不知道如何为特定的URL设置时间 即使我真的喜欢: map '/foo/bar' do Rack::Timeout.timeout = 10 end 映射“/foo/bar”do 机架::超时。超时=10 结束 不仅是/foo/bar动作,而且每个动作都会在10秒后消失 是否可以为特定URL设置超时? 或者我应该使用机架超时以外的其他解决方案吗?如果您担心特定操作运行时间过长,我会将相关代码包装在超时块中,而不是尝试在URL级别强制执行超时。您可以轻松地将下面

我使用机架超时,工作正常。 但我不知道如何为特定的URL设置时间

即使我真的喜欢:

map '/foo/bar' do Rack::Timeout.timeout = 10 end 映射“/foo/bar”do 机架::超时。超时=10 结束 不仅是/foo/bar动作,而且每个动作都会在10秒后消失

是否可以为特定URL设置超时?
或者我应该使用机架超时以外的其他解决方案吗?

如果您担心特定操作运行时间过长,我会将相关代码包装在超时块中,而不是尝试在URL级别强制执行超时。您可以轻松地将下面的内容包装成一个helper方法,并在整个控制器中使用一个可变超时

require "timeout'"
begin
  status = Timeout::timeout(10) {
  # Potentially long process here...
}
rescue Timeout::Error
  puts 'This is taking way too long.'
end

将此代码作为timeout.rb放在config/initializers文件夹下,并将特定url放在数组上

require RUBY_VERSION < '1.9' && RUBY_PLATFORM != "java" ? 'system_timer' : 'timeout'
SystemTimer ||= Timeout

module Rack
  class Timeout
    @timeout = 30
    @excludes = ['your url here',
                 'your url here'
    ]

    class << self
      attr_accessor :timeout, :excludes
    end

    def initialize(app)
      @app = app
    end

    def call(env)
      #puts 'BEGIN CALL'
      #puts  env['REQUEST_URI']
      #puts 'END CALL'

      if self.class.excludes.any? {|exclude_uri| /#{exclude_uri}/ =~ env['REQUEST_URI']}
        @app.call(env)
      else
        SystemTimer.timeout(self.class.timeout, ::Timeout::Error) { @app.call(env) }
      end
    end

  end
end
需要RUBY_版本<'1.9'和&RUBY_平台!=“java”?'系统计时器“:“超时”
系统计时器| |=超时
模块机架
类超时
@超时=30
@excludes=['您的url在此',
'您的url在此'
]

类吉滕·科塔里答案的更新版本:

module Rack
  class Timeout
    @excludes = [
      '/statistics',
    ]

    class << self
      attr_accessor :excludes
    end

    def call_with_excludes(env)
      #puts 'BEGIN CALL'
      #puts  env['REQUEST_URI']
      #puts 'END CALL'

      if self.class.excludes.any? {|exclude_uri| /\A#{exclude_uri}/ =~ env['REQUEST_URI']}
        @app.call(env)
      else
        call_without_excludes(env)
      end
    end

    alias_method_chain :call, :excludes

  end
end
模块机架
类超时
@排除=[
“/统计数据”,
]

顺便说一句,我用的是Heroku。