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

Instance Method Details

#online?(uri: 'https://www.google.com/generate_204', ttl: 300, timeout: 10) ⇒ Boolean

Note:

The method has a 10-second timeout to prevent hanging on slow connections

Note:

Returns false for any network-related errors including timeouts, DNS failures, and unreachable hosts

Note:

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.

Examples:

Basic usage - check internet connectivity

if online?
  puts "Connected to the internet!"
else
  puts "No internet connection available"
end

Check connectivity to a specific service

if online?('https://api.github.com')
  # Proceed with GitHub API calls
else
  # Use cached data or show offline message
end

Check with custom cache TTL (10 minutes)

if online?(ttl: 600)
  # Will use cached result for 10 minutes
end

Use in Minitest tests

require 'minitest/autorun'
require 'online'

class MyServiceTest < Minitest::Test
  def test_api_call_when_online
    skip("No internet connection") unless online?
    # Test code that requires internet
  end

  def test_offline_fallback
    unless online?
      assert_equal cached_data, service.fetch_data
    end
  end
end

Conditional feature loading

class WeatherWidget
  def display
    if online?('https://api.weather.com')
      show_live_weather
    else
      show_cached_weather
    end
  end
end

Parameters:

  • uri (String) (defaults to: 'https://www.google.com/generate_204')

    the URI to check connectivity against (default: ‘www.google.com/generate_204’)

  • ttl (Integer) (defaults to: 300)

    time-to-live for cached results in seconds (default: 300 seconds = 5 minutes)

  • timeout (Integer) (defaults to: 10)

    open, read and write HTTP timeout (default: 10 seconds)

Returns:

  • (Boolean)

    true if the URI is reachable and returns HTTP success, false otherwise



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