Module: Kernel
- Defined in:
- lib/online.rb
Overview
Checks whether we are online now.
- Author
-
Yegor Bugayenko ([email protected])
- Copyright
-
Copyright © 2024-2025 Yegor Bugayenko
- License
-
MIT
Defined Under Namespace
Modules: OnlineOrOffline
Instance Method Summary collapse
-
#online?(uri: 'https://www.google.com/generate_204', ttl: 300, timeout: 10) ⇒ Boolean
Checks whether the system has an active internet connection by attempting to connect to a specified URI.
Instance Method Details
#online?(uri: 'https://www.google.com/generate_204', ttl: 300, timeout: 10) ⇒ Boolean
The method has a 10-second timeout to prevent hanging on slow connections
Returns false for any network-related errors including timeouts, DNS failures, and unreachable hosts
Results are cached with a default TTL of 5 minutes to reduce network requests
Checks whether the system has an active internet connection by attempting to connect to a specified URI.
This method performs an HTTP GET request to verify connectivity. It’s useful for checking internet availability before performing network-dependent operations or for implementing offline-mode functionality in applications.
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 |
# File 'lib/online.rb', line 89 def online?(uri: 'https://www.google.com/generate_204', ttl: 300, timeout: 10) raise 'The URI is nil' if uri.nil? raise 'The TTL is nil' if ttl.nil? key = uri.to_s OnlineOrOffline.mutex.synchronize do entry = OnlineOrOffline.cache[key] return entry[:status] if entry && (Time.now - entry[:time]) < ttl uri = URI(uri) unless uri.is_a?(URI) status = begin Net::HTTP.start( uri.hostname, uri.port, use_ssl: uri.scheme == 'https', open_timeout: timeout, read_timeout: timeout, write_timeout: timeout ) do |http| http.request_get(uri, {}).is_a?(Net::HTTPSuccess) end rescue \ Socket::ResolutionError, Net::OpenTimeout, Net::ReadTimeout, Net::WriteTimeout, Errno::EHOSTUNREACH, Errno::EINVAL, Errno::EADDRNOTAVAIL, Errno::EBADF false end OnlineOrOffline.cache[key] = { status: status, time: Time.now } status end end |