18

刚刚询问如何使用javascript检查是否存在互联网连接并得到了一些很好的答案。在 Ruby 中最简单的方法是什么?在尝试使生成的 html 标记代码尽可能干净时,我想根据互联网条件是否有条件地呈现 javascript 文件的脚本标记。类似的东西(这是 HAML):

- if internet_connection?
    %script{:src => "http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js", :type => "text/javascript"}
- else
    %script{:src => "/shared/javascripts/jquery/jquery.js", :type => "text/javascript"}
4

7 回答 7

20
require 'open-uri'

def internet_connection?
  begin
    true if open("http://www.google.com/")
  rescue
    false
  end
end

这更接近 OP 正在寻找的内容。它适用于 Ruby 1.8 和 1.9。它也有点干净。

于 2011-11-29T21:15:43.567 回答
14

我喜欢每个人都简单地假设谷歌服务器已经启动。对谷歌的信任。

如果你想知道你是否有互联网而不依赖谷歌,那么你可以使用 DNS 来查看你是否能够获得连接。

您可以使用Ruby DNS Resolv尝试将 url 转换为 ip 地址。适用于 Ruby 版本 1.8.6+

所以:

#The awesome part: resolv is in the standard library

def has_internet?
  require "resolv"
  dns_resolver = Resolv::DNS.new()
  begin
    dns_resolver.getaddress("symbolics.com")#the first domain name ever. Will probably not be removed ever.
    return true
  rescue Resolv::ResolvError => e
    return false
  end
end

希望这可以帮助某人:)

于 2014-04-03T12:11:24.053 回答
7

你可以使用Ping类。

require 'resolv-replace'
require 'ping'

def internet_connection?
  Ping.pingecho "google.com", 1, 80
end

该方法返回trueorfalse并且不引发异常。

于 2010-03-05T09:53:58.593 回答
4

Simone Carletti 的答案相同,但与Ruby 2兼容:

# gem install "net-ping"

require "net/ping"

def internet_connection?
  Net::Ping::External.new("8.8.8.8").ping?
end
于 2015-07-09T13:32:46.570 回答
1
require 'open-uri'

page = "http://www.google.com/"
file_name = "output.txt"
output = File.open(file_name, "a")
begin
  web_page = open(page, :proxy_http_basic_authentication => ["http://your.company.proxy:80/", "your_user_name", "your_user_password"])  
  output.puts "#{Time.now}: connection established - OK !" if web_page
rescue Exception
  output.puts "#{Time.now}: Connection failed !"
  output.close
ensure
  output.close
end
于 2011-02-14T15:31:53.433 回答
0

我试图找到与您类似的问题的解决方案,但找不到任何解决方案。不幸的是,Ping.pingecho由于某种我不知道的原因,该方法对我不起作用。我想出了一个解决方案。使用httparty. 我想把它放在一个模块中,所以这样做了,它工作得很好

# gem install httparty
require "httparty"

module Main
  def Main.check_net
    begin
      a = HTTParty.get("https://www.google.com")
      if a.length() >= 100
        puts "online"
      end
    rescue SocketError
      puts "offline"
    end
  end
end

include Main
Main.check_net

Google 的套接字错误可能不会发生,因此此方法将起作用

于 2021-07-08T17:57:05.027 回答
-1
def connected?
  !!Socket.getaddrinfo("google.com", "http")  
rescue SocketError => e
  e.message != 'getaddrinfo: nodename nor servname provided, or not known'
end

由于它使用主机名,它需要做的第一件事是 DNS 查找,如果没有 Internet 连接,则会导致异常。

于 2014-04-03T13:05:08.903 回答