Module: Optica::Client

Defined in:
lib/optica/client.rb,
lib/optica/client/cli.rb,
lib/optica/client/config.rb,
lib/optica/client/request.rb,
lib/optica/client/version.rb,
lib/optica/client/fetch_json.rb

Defined Under Namespace

Classes: CLI, Config, Request

Constant Summary collapse

VERSION =
"0.1.4".freeze

Class Method Summary collapse

Class Method Details

.fetch_json(uri) ⇒ Any

Fetch the JSON data at the given URI. Blocks.

As data is received, yeilds the data chunk (a string) and the completion ratio (a float).

Returns:

  • (Any)

    the parsed JSON



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/optica/client/fetch_json.rb', line 13

def self.fetch_json(uri)
  io = StringIO.new

  Net::HTTP.start(
    uri.host,
    uri.port,
    use_ssl: uri.scheme == 'https'
  ) do |http|
    req = Net::HTTP::Get.new(uri)

    http.request(req) do |res|
      file_size = res['content-length'].to_i
      downloaded = 0.0

      res.read_body do |chunk|
        io.write chunk
        downloaded += chunk.size
        ratio = downloaded / file_size
        yield(chunk, ratio) if block_given?
      end
    end
  end

  JSON.parse(io.string)
end