Module: LinkShrink::Request

Included in:
LinkShrink
Defined in:
lib/link_shrink/request.rb

Overview

Handles request and calls parser

Author:

Class Method Summary collapse

Class Method Details

.included(base) ⇒ Object



7
8
9
# File 'lib/link_shrink/request.rb', line 7

def self.included(base)
  base.extend self
end

.parse(response, shrinker) ⇒ Object



17
18
19
20
21
22
23
24
25
# File 'lib/link_shrink/request.rb', line 17

def parse(response, shrinker)
  if shrinker.content_type.eql?('text/plain')
    response
  else
    process_response(response, shrinker)
  end
rescue
  "Error #{response}"
end

.process_parse_options(parsed_json, shrinker) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
# File 'lib/link_shrink/request.rb', line 27

def process_parse_options(parsed_json, shrinker)
  if shrinker.collection_key && shrinker.url_key
    parsed_json
      .fetch(shrinker.collection_key)
      .fetch(shrinker.url_key)
  else
    parsed_json.fetch(shrinker.url_key)
  end
rescue
  parsed_json.fetch(shrinker.error_key) { 'Error parsing the request!'}
end

.process_request(url, shrinker = LinkShrink::Config.api) ⇒ Object



13
14
15
# File 'lib/link_shrink/request.rb', line 13

def process_request(url, shrinker = LinkShrink::Config.api)
  parse(request(url, shrinker).body, shrinker)
end

.process_response(response, shrinker, json = JSONParser) ⇒ Object



39
40
41
42
# File 'lib/link_shrink/request.rb', line 39

def process_response(response, shrinker, json = JSONParser)
  parsed_json = json.parse_json(response)
  process_parse_options(parsed_json, shrinker.class)
end

.request(new_url, shrinker) ⇒ Object

Calls URL API



47
48
49
50
51
52
53
54
55
# File 'lib/link_shrink/request.rb', line 47

def request(new_url, shrinker)
  shrinker.url = new_url
  Typhoeus::Request.new(
    shrinker.api_url,
    method:  shrinker.http_method,
    body:    shrinker.body_parameters(shrinker.url),
    headers: { 'Content-Type' => shrinker.content_type }
  ).run
end