Sha256: 9d2cde32d7df4a4f6e70b0de94e9938efbe5c95c5ea65cfd6d91eeb5234077d4

Contents?: true

Size: 1.45 KB

Versions: 1

Compression:

Stored size: 1.45 KB

Contents

# frozen_string_literal: true

require 'json'
require 'net/http'

module CoreExtensions
  module Net
    module HTTPResponse
      module WeatherResponse
        # rdoc
        # Returns the weather
        def weather
          parse_weather
          @weather
        end

        # rdoc
        # Returns the response code
        def weather_code
          parse_weather

          return (weather['cod'] || '500').to_i if weather.is_a? Hash

          200
        end

        # rdoc
        # Returns the response message
        def weather_message
          parse_weather
          return weather['message'] if weather.is_a? Hash

          'None'
        end

        # rdoc
        # Returns boolean if the response contains an error or not.
        def error?
          weather_code != 200
        end

        private

        # rdoc
        # Sets the weather variable
        def weather=(weather)
          @weather = weather if @weather.nil?
        end

        # rdoc
        # Attempts to parse the body to JSON.  This is so we don't have to continually
        # parse the raw JSON.
        def parse_weather
          # Try to parse the response and return a hash
          @weather = JSON.parse(body)
        rescue StandardError
          # Return the body string if parsing fails (used for html and xml responses)
          @weather = body
        end
      end
    end
  end
end

Net::HTTPResponse.include CoreExtensions::Net::HTTPResponse::WeatherResponse

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
owmo-2.1.1 lib/core_extensions/net/http_response/weather_response.rb