Sha256: 907ad81446dba61a0aeab0e00477013a425b3528d561206b58c9bc255e4ed8ab

Contents?: true

Size: 1.44 KB

Versions: 3

Compression:

Stored size: 1.44 KB

Contents

#
# Author: Seth Vargo <sethvargo@gmail.com>
#
# Copyright 2014 Chef Software, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

require 'json'
require 'open-uri'
require 'socket'

module Falcore
  class Fetcher
    class << self
      #
      # Get the JSON at the given URL and parse it as such. This method is just
      # a very thin wrapper around Ruby's native +OpenURI+ with some error-
      # handling magic.
      #
      # @raise [RuntimeError]
      #   if the request fails (40X, 50X, bad-URL) or if the JSON is invalid
      #
      # @param [String] url
      #   the url to get
      #
      # @return [Hash]
      #   the parsed JSON hash
      #
      def get(url)
        response = open(url)
        JSON.parse(response.read)
      rescue Errno::ENOENT, OpenURI::HTTPError, SocketError => e
        raise "Failed to GET '#{url}': #{e.class} - #{e.message}"
      rescue JSON::ParserError
        raise 'Invalid JSON!'
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
falcore-0.2.0 lib/falcore/fetcher.rb
falcore-0.1.1 lib/falcore/fetcher.rb
falcore-0.1.0 lib/falcore/fetcher.rb