Sha256: 4af2e3fb1c8a6453c22edc346572c6b14e74d1dd3a7f46a22fcc2fb5e3d6520a

Contents?: true

Size: 1.02 KB

Versions: 4

Compression:

Stored size: 1.02 KB

Contents

require 'open-uri'
require 'json'

module CoderWally
  # API Class
  class API
    attr_reader :response
    def initialize
      @response = {}
    end

    # Fetch data from CoderWall
    def fetch(username)
      @response.fetch(username) do
        uri = uri_for_user(username)
        json = send_request(uri)

        begin
          @response[username] = JSON.parse(json.read)
        rescue JSON::ParserError
          raise InvalidJson, 'Received invalid json in response'
        end
      end
    end

    private

    # Dispatch the request
    def send_request(url)
      open(url)
    rescue OpenURI::HTTPError => error
      ExceptionHandler.new(error)
    end

    # Build user URI from username and api url
    def uri_for_user(username)
      fail 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 bad JSON
class InvalidJson < StandardError
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
coder_wally-1.0.2 lib/coder_wally/api.rb
coder_wally-1.0.1 lib/coder_wally/api.rb
coder_wally-1.0.0 lib/coder_wally/api.rb
coder_wally-0.1.2 lib/coder_wally/api.rb