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 に答える
7

Pingクラスを使用できます。

require 'resolv-replace'
require 'ping'

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

このメソッドはtrue、またはfalse例外を発生させません。

于 2010-03-05T09:53:58.593 に答える
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 に答える