Module: Manga::Tools::Http

Defined in:
lib/manga/tools/http.rb

Overview

HTTP client class

Class Method Summary collapse

Class Method Details

.connection(url, session_id) ⇒ Faraday::Connection

Returns a connection object.

Parameters:

  • url (String)

    an url string, eg: ‘example.com`

  • session_id (String, nil)

    A Session ID string or nil

Returns:

  • (Faraday::Connection)

    a connection object



14
15
16
17
18
19
20
21
22
# File 'lib/manga/tools/http.rb', line 14

def self.connection(url, session_id)
  headers = { 'User-Agent' => user_agent }
  headers['X-Session-ID'] = session_id if session_id

  @connection = Faraday.new(url: url, headers: headers) do |f|
    # f.response :logger
    f.response :raise_error
  end
end

.connection_url(url) ⇒ String

If the port is not a standard port (80 or 443), the port number is included.

Parameters:

  • url (URI)

    A URL instance.

Returns:

  • (String)

    Returns the URL to connect to.



45
46
47
48
49
50
51
# File 'lib/manga/tools/http.rb', line 45

def self.connection_url(url)
  if [80, 443].include?(url.port)
    "#{url.scheme}://#{url.host}"
  else
    "#{url.scheme}://#{url.host}:#{url.port}"
  end
end

.get(url, session_id) ⇒ Faraday::Response

Returns a response object.

Parameters:

Returns:

  • (Faraday::Response)

    a response object



27
28
29
30
# File 'lib/manga/tools/http.rb', line 27

def self.get(url, session_id)
  u = URI.parse(url)
  connection(connection_url(u), session_id).get(u.request_uri)
end

.post(url, session_id, params) ⇒ Object



32
33
34
35
36
37
38
39
# File 'lib/manga/tools/http.rb', line 32

def self.post(url, session_id, params)
  u = URI.parse(url)
  connection(connection_url(u), session_id).post do |req|
    req.headers['Content-Type'] = 'application/json'
    req.url u.request_uri
    req.body = params.to_json
  end
end

.user_agentString

Returns a user agent string

Returns:

  • (String)

    Returns a user agent string



54
55
56
# File 'lib/manga/tools/http.rb', line 54

def self.user_agent
  @user_agent ||= "manga-tools #{Manga::Tools::VERSION}"
end