Created
May 22, 2023 21:58
-
-
Save jqr/d8fe0764a1d8d5c3b8b7213082bbbd69 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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