Class: Resync::Client::HTTPHelper

Inherits:
Object
  • Object
show all
Defined in:
lib/resync/client/http_helper.rb

Overview

Utility class simplifying GET requests for HTTP/HTTPS resources.

Constant Summary collapse

DEFAULT_MAX_REDIRECTS =

The default number of redirects to follow before erroring out.

5

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(user_agent:, redirect_limit: DEFAULT_MAX_REDIRECTS) ⇒ HTTPHelper

Creates a new HTTPHelper

Parameters:

  • user_agent (String)

    the User-Agent string to send when making requests

  • redirect_limit (Integer) (defaults to: DEFAULT_MAX_REDIRECTS)

    the number of redirects to follow before erroring out (defaults to DEFAULT_MAX_REDIRECTS)



36
37
38
39
# File 'lib/resync/client/http_helper.rb', line 36

def initialize(user_agent:, redirect_limit: DEFAULT_MAX_REDIRECTS)
  @user_agent = user_agent
  @redirect_limit = redirect_limit
end

Instance Attribute Details

#redirect_limitInteger

Returns the number of redirects to follow before erroring out.

Returns:

  • (Integer)

    the number of redirects to follow before erroring out



26
27
28
# File 'lib/resync/client/http_helper.rb', line 26

def redirect_limit
  @redirect_limit
end

#user_agentString

Returns the User-Agent string to send when making requests.

Returns:

  • (String)

    the User-Agent string to send when making requests



22
23
24
# File 'lib/resync/client/http_helper.rb', line 22

def user_agent
  @user_agent
end

Instance Method Details

#fetch(uri:, limit: redirect_limit) ⇒ String

Gets the content of the specified URI as a string.

Parameters:

  • uri (URI)

    the URI to download

  • limit (Integer) (defaults to: redirect_limit)

    the number of redirects to follow (defaults to #redirect_limit)

Returns:

  • (String)

    the content of the URI



48
49
50
51
52
53
54
# File 'lib/resync/client/http_helper.rb', line 48

def fetch(uri:, limit: redirect_limit)
  make_request(uri, limit) do |success|
    # not 100% clear why we need an explicit return here; it
    # doesn't show up in unit tests but it does in example.rb
    return success.body
  end
end

#fetch_to_file(uri:, path: nil, limit: redirect_limit) ⇒ String

Gets the content of the specified URI and saves it to a file. If no file path is provided, saves it to a temporary file.

Parameters:

  • uri (URI)

    the URI to download

  • path (String) (defaults to: nil)

    the path to save the download to (optional)

Returns:

  • (String)

    the path to the downloaded file



61
62
63
64
65
66
67
68
69
# File 'lib/resync/client/http_helper.rb', line 61

def fetch_to_file(uri:, path: nil, limit: redirect_limit)
  make_request(uri, limit) do |success|
    file = path ? File.new(path, 'w+') : Tempfile.new(['resync-client', ".#{extension_for(success)}"])
    open file, 'w' do |out|
      success.read_body { |chunk| out.write(chunk) }
    end
    return file.path
  end
end