views:

182

answers:

1

Just asked how to check if an internet connection exists using javascript and got some great answers. What's the easiest way to do this in Ruby? In trying to make generated html markup code as clean as possible, I'd like to conditionally render the script tag for javascript files depending on whether or not an internet condition. Something like (this is 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"}
+2  A: 

You can use the Ping class.

require 'resolv-replace'
require 'ping'

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

The method returns true or false and doesn't raise exceptions.

Simone Carletti
Why the need to require 'resolv-replace'? Also, 'ping' has been dropped from the 1.9 standard lib. I came up with a simple enough work around [here](http://github.com/myronmarston/vcr/commit/30b6242a1b0e97a21c27808e416e9b9e8215f994)...but if there's a better way to do this for 1.9, let me know.
Myron
See http://github.com/mperham/em-resolv-replace
Simone Carletti