Sha256: 9f7bd1c6602566017bd6502bec6937866538e59d9aa44ef7de561f769bfff92e
Contents?: true
Size: 1.87 KB
Versions: 3
Compression:
Stored size: 1.87 KB
Contents
require "uri" require "net/http" require "json" module Openweather2 class << self attr_accessor :configuration end class Configuration attr_accessor :endpoint attr_accessor :apikey end class UnprocessableError < RuntimeError; end class ForbiddenError < RuntimeError; end class UnknownResponse < RuntimeError; end extend self def configure self.configuration ||= Configuration.new yield(configuration) end def weather(city) configure_required! uri = URI(Openweather2.configuration.endpoint) uri.query = URI.encode_www_form(default_params.merge(:q => city)) req = Net::HTTP::Get.new(uri.request_uri) http_params = [uri.hostname, uri.port, use_ssl: uri.scheme == 'https'] res = Net::HTTP.start(*http_params) do |http| http.request(req) end case res when Net::HTTPSuccess json = JSON.parse(res.body) Openweather2::Weather.new(json) when Net::HTTPUnprocessableEntity raise UnprocessableError, "Bad URI param!" else raise UnknownResponse, "Something was wrong!" end end private def configure_required! if Openweather2.configuration.instance_variables.size < 2 raise ArgumentError, "You must configure Openweather2" end end def default_params {:APPID => Openweather2.configuration.apikey } end def do_request(req) configure_required! endpoint_uri = URI(Openweather2.configuration.endpoint) http_params = [ endpoint_uri.hostname, endpoint_uri.port, use_ssl: uri.scheme == 'https' ] res = Net::HTTP.start(*http_params) do |http| http.request(req) end case res when Net::HTTPSuccess JSON.parse(res.body) when Net::HTTPUnprocessableEntity raise UnprocessableError, "Bad URI param!" else raise UnknownResponse, "Something was wrong!" end end end
Version data entries
3 entries across 3 versions & 1 rubygems
Version | Path |
---|---|
openweather2-0.1.3 | lib/openweather2/client.rb |
openweather2-0.1.2 | lib/openweather2/client.rb |
openweather2-0.1.1 | lib/openweather2/client.rb |