Heads up: This description was created by AI and might not be 100% accurate.
response_code_2xx.rb
This Ruby code snippet demonstrates a function rc2xx?
that checks if a given URI returns a successful HTTP status code (200-299). It uses Net::HTTP
to make a GET request to the URI, parses the URL, handles HTTPS connections, and then verifies the HTTP status code returned. The function returns true
if the status code is within the 200-299 range, indicating success, and false
otherwise. The example call rc2xx?("https://yumayx.github.io/")
returns true
because the website responds with a successful status code.
Ruby code snippet
require "net/http"
#=> true
def rc2xx?(uri)
url = URI.parse(uri)
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = (url.scheme == "https")
request = Net::HTTP::Get.new(url.path)
response = http.request(request)
response_code = response.code.to_i
response_code >= 200 && response_code < 300
end
#=> :rc2xx?
rc2xx?("https://yumayx.github.io/")
#=> true
Executed with Ruby 3.4.5
.