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
How to Make a Post Request with Open-Uri
Get Sidekiq to Execute a Job Immediately
Rails Unable to Convert Unpermitted Parameters to Hash
Ruby: Combine Date and Time Objects into a Datetime
Do I Have to Manually Uninstall All Dependent Gems
When (If) to Consolidate Activerecord Migrations
How to Overwrite a Printed Line in the Shell with Ruby
How to Create Wizard Forms in Ruby on Rails
How to Traverse Symlinked Directories in Ruby with a "**" Glob
How to Find Each Instance of a Class in Ruby
Ruby Hash Autovivification (Facets)
Problems Setting a Custom Primary Key in a Rails 4 Migration