Check If Internet Connection Exists with Ruby

Check if Internet Connection Exists with Ruby?

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.

Checking for internet connection

You could try using Net::HTTP and 'pinging' a reliable URL such as Google and check for an exception indicating they do not have an internet connection.

Ruby on Rails : check whether internet connection in on or off?

I don't fancy that you check for a connection. As you said, when there is no connection to rails and the remote mail server (or dns) rails throws an exception. So you should catch that exception and handle it accordingly.

def create
@vendor = Vendor.new(params[:vendor])
if @vendor.save
begin
VendorMailer.registration_confirmation(@vendor).deliver
flash[:success] = "Vendor Added Successfully"
redirect_to amain_path
rescue SocketError => e
flash[:success] = "Vendor Added Successfully mail is not send"
redirect_to amain_path
end
else
render 'new'
end
end

Check if URL exists in Ruby

Use the Net::HTTP library.

require "net/http"
url = URI.parse("http://www.google.com/")
req = Net::HTTP.new(url.host, url.port)
res = req.request_head(url.path)

At this point res is a Net::HTTPResponse object containing the result of the request. You can then check the response code:

do_something_with_it(url) if res.code == "200"

Note: To check for https based url, use_ssl attribute should be true as:

require "net/http"
url = URI.parse("https://www.google.com/")
req = Net::HTTP.new(url.host, url.port)
req.use_ssl = true
res = req.request_head(url.path)

Ruby - Test whether database connection is possible

You can check if the connection is possible by running the following script:

require './config/environment.rb' # Assuming the script is located in the root of the rails app
begin
ActiveRecord::Base.establish_connection # Establishes connection
ActiveRecord::Base.connection # Calls connection object
puts "CONNECTED!" if ActiveRecord::Base.connected?
puts "NOT CONNECTED!" unless ActiveRecord::Base.connected?
rescue
puts "NOT CONNECTED!"
end


Related Topics



Leave a reply



Submit