Add Utils::Internet.connected? to determine whether host machine has internet connection. (#5870)

Merge pull request 5870
This commit is contained in:
Parker Moore 2017-11-02 16:54:42 -04:00 committed by jekyllbot
parent 7e31e274fb
commit 8fc463bdce
3 changed files with 46 additions and 0 deletions

View File

@ -6,6 +6,7 @@ module Jekyll
extend self
autoload :Ansi, "jekyll/utils/ansi"
autoload :Exec, "jekyll/utils/exec"
autoload :Internet, "jekyll/utils/internet"
autoload :Platforms, "jekyll/utils/platforms"
autoload :Rouge, "jekyll/utils/rouge"
autoload :WinTZ, "jekyll/utils/win_tz"

View File

@ -0,0 +1,39 @@
# frozen_string_literal: true
module Jekyll
module Utils
module Internet
# Public: Determine whether the present device has a connection to
# the Internet. This allows plugin writers which require the outside
# world to have a neat fallback mechanism for offline building.
#
# Example:
# if Internet.connected?
# Typhoeus.get("https://pages.github.com/versions.json")
# else
# Jekyll.logger.warn "Warning:", "Version check has been disabled."
# Jekyll.logger.warn "", "Connect to the Internet to enable it."
# nil
# end
#
# Returns true if a DNS call can successfully be made, or false if not.
module_function
def connected?
!dns("example.com").nil?
end
private
module_function
def dns(domain)
require "resolv"
Resolv::DNS.open do |resolver|
resolver.getaddress(domain)
end
rescue Resolv::ResolvError, Resolv::ResolvTimeout
nil
end
end
end
end

View File

@ -403,4 +403,10 @@ class TestUtils < JekyllUnitTest
assert_equal "bom|another", merged[:encoding]
end
end
context "Utils::Internet.connected?" do
should "return true if there's internet" do
assert Utils::Internet.connected?
end
end
end