Skip to content

Instantly share code, notes, and snippets.

@jqr
Created May 22, 2023 21:58
Show Gist options
  • Save jqr/d8fe0764a1d8d5c3b8b7213082bbbd69 to your computer and use it in GitHub Desktop.
Save jqr/d8fe0764a1d8d5c3b8b7213082bbbd69 to your computer and use it in GitHub Desktop.
class Current < ActiveSupport::CurrentAttributes
attribute :interactive_timeout_remaining
end
class ApplicationController < ActionController::Base
before_action :set_interactive_timeout_remaining
def set_interactive_timeout_remaining
Current.interactive_timeout_remaining = 5.seconds
end
end
module InteractiveTimeout
# Wrap API operations, yields remaining time if set.
# WARNING: can be negative.
def self.tracking
if remaining = Current.interactive_timeout_remaining
start = Time.current
end
yield(remaining)
ensure
if remaining
duration = Time.current - start
Current.interactive_timeout_remaining -= duration
end
end
end
class SomeApi
def execute
InteractiveTimeout.tracking do |timeout|
faraday_connection.timeout(timeout || 30.seconds).get
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment