Sha256: 43ad0970c051e11becea046c5e69da1d89806721bc1b2b6f9b931d7224da71bf

Contents?: true

Size: 1.87 KB

Versions: 1

Compression:

Stored size: 1.87 KB

Contents

require 'uri'
require 'net/http'
require 'json'

module OW

  class << self
    attr_accessor :configuration
  end

  class Configuration
    attr_accessor :endpoint, :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 get_weather(options={})
    check_configuration!
    uri = set_params(options)
    response = send_request(uri)
    parse_json(response)
  end

  private  
  def parse_json(response)
    case response
    when Net::HTTPSuccess
      check_response(response)
    when Net::HTTPUnprocessableEntity
      raise UnprocessableError, 'Bad URI param!'
    else
      raise UnknownResponse, 'Something was wrong!'
    end
  end

  def check_response(response)
    json = JSON.parse(response.body)
    if json['cod'] == 200
      OW::Weather.new(json)
    else
      nil
    end
  end

  def send_request(uri)
    req = Net::HTTP::Get.new(uri.request_uri)
    http_params = [uri.hostname, uri.port, use_ssl: uri.scheme == 'https']
    Net::HTTP.start(*http_params) {|http| http.request(req)}
  end

  def set_params(options)
    uri = URI(OW.configuration.endpoint)
    uri.query = URI.encode_www_form(default_params.merge(lat: options[:lat], lon: options[:lon], units: options[:units])) if options[:lat] && options[:lon]
    uri.query = URI.encode_www_form(default_params.merge(zip: options[:zip], units: options[:units])) if options[:zip]
    uri.query = URI.encode_www_form(default_params.merge(q: options[:city], units: options[:units])) if options[:city]
    uri
  end

  def check_configuration!
    if OW.configuration.instance_variables.size < 2
      raise ArgumentError, 'You must configure OW'
    end
  end

  def default_params
    {APPID: OW.configuration.apikey}
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
oweather-0.1.0 lib/OW/client.rb