Question

I am using net/http in rails to get back the response codes from URL's with the following code;

require "net/http"
require "uri"


class Status
def initialize(url)
    @url = url
end

def get_status 
    begin 
        response.code
    rescue Exception => e
        Rails.logger.info("Error #{e}")
    end
end

def active?
    ["200","203","302","301"].include?(get_status) ? true : false
end

private

def lookup
    URI.parse(@url)
end
def http
    Net::HTTP.new(lookup.host, lookup.port)
end
def request
    Net::HTTP::Get.new(lookup.request_uri)
end
def response
    http.request(request)
end
end

Although it correctly marks failures it displays the code for all whether pass or failure as status code: 200, how can I get the correct status code?

Controller:

class EnvironmentsController < ApplicationController
  def status
    app = App.find(params[:app_id])
    environment = app.environments.find{|env| env.id.to_s == params[:id]}
    render json: {up:environment.up?}
  end
end

View:

<%- App.all.each do |app| %>
  <h3><%= app.name %></h3>

  <ul class="app" data-app-id="<%= app.id %>">
    <%- app.environments.each do |environment| %>
      <li class="env" data-env-id="<%= environment.id %>">
      <strong><%= environment.name %></strong>
      <%= environment.url %><span class="status"> Loading. . . </span>
      <!-- <i> Status Code: <% puts response.code %></i> </li> -->
    <% end %>
  </ul>
Was it helpful?

Solution

You are not using your Status class. In your view response refers to the current response.

So instead of:

Status Code: <% puts response.code %>

Try:

Status Code: <%= Status.new(environment.url).get_status %>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top