Friday 2 December 2016

Rails check url exist or check image exist on following url ruby on rails

http://stackoverflow.com/questions/5908017/check-if-url-exists-in-ruby



require "net/http"

def url_exist?(url_string)
  url = URI.parse(url_string)
  req = Net::HTTP.new(url.host, url.port)
  req.use_ssl = (url.scheme == 'https')
  path = url.path if url.path.present?
  res = req.request_head(path || '/')
  if res.kind_of?(Net::HTTPRedirection)
    url_exist?(res['location']) # Go after any redirect and make sure you can access the redirected URL  else    ! %W(4 5).include?(res.code[0]) # Not from 4xx or 5xx families  endrescue Errno::ENOENT  false #false if can't find the serverend

def url_exist_second?(url)
  uri = URI(url)

  request = Net::HTTP.new uri.host
  response= request.request_head uri.path
  return response.code.to_i == 200end
=========================================
Calling Helper  function :
url_exist?("url_string")
 
 
 
 ===================================Second Solution and better one==============================
File.file?(Url_string) 

No comments:

Post a Comment