Sha256: 59484937397a157b2e552d0c3473f5bc3d64aed77dc1ee5a5e81173de61f96d3

Contents?: true

Size: 1.54 KB

Versions: 1

Compression:

Stored size: 1.54 KB

Contents

require 'open-uri'
require 'json'

module CoderWally
  # API Class
  class API
    # Fetch data from CoderWall
    def fetch(username)
      uri = uri_for_user(username)
      json = send_request(uri)

      begin
        JSON.parse(json.read)
      rescue JSON::ParserError => error
        raise InvalidJson, 'Received invalid json in response'
      end
    end

    private
      # Dispatch the request
      def send_request(url)
        begin
          open(url)
        rescue OpenURI::HTTPError => error
          handle_user_not_found_error(error)
          handle_server_error(error)
        end
      end

      # Parse status code from error
      def get_status_code(error)
        error.io.status[0]
      end

      # Raise server error
      def handle_server_error(error)
        raise ServerError, 'Server error' if  get_status_code(error) == '500'
      end

      # Raise user not found error
      def handle_user_not_found_error(error)
        raise UserNotFoundError, 'User not found' if  get_status_code(error) == '404'
      end

      # Build user URI from username and api url
      def uri_for_user(username)
        raise(ArgumentError, 'Please provide a username') if username.empty?

        URI.parse(api_url % username)
      end

      # The URL of the API we'll use.
      def api_url
        'https://coderwall.com/%s.json'
      end
  end
end
# Handles user not found exception
class UserNotFoundError < StandardError
end

# Handles server exception
class ServerError < StandardError
end
# Handles bad JSON
class InvalidJson < StandardError
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
coder_wally-0.1.0 lib/coder_wally/api.rb