Check if Internet Connection Exists with Ruby?

browser, internet-connection, ruby

Solution

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.

Problem

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"} ```

Original source

Related problems