Module: CC::Service::HTTP

Extended by:
ActiveSupport::Concern
Included in:
CC::Service
Defined in:
lib/cc/service/http.rb

Defined Under Namespace

Modules: ClassMethods

Instance Method Summary collapse

Instance Method Details

#ca_fileObject

Gets the path to the SSL Certificate Authority certs. These were taken from: curl.haxx.se/ca/cacert.pem

Returns a String path.



83
84
85
# File 'lib/cc/service/http.rb', line 83

def ca_file
  @ca_file ||= ENV.fetch("CODECLIMATE_CA_FILE", File.expand_path('../../../../config/cacert.pem', __FILE__))
end

#http(options = {}) ⇒ Object



59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/cc/service/http.rb', line 59

def http(options = {})
  @http ||= begin
    config = self.class.default_http_options
    config.each do |key, sub_options|
      next if key == :adapter
      sub_hash = options[key] ||= {}
      sub_options.each do |sub_key, sub_value|
        sub_hash[sub_key] ||= sub_value
      end
    end
    options[:ssl][:ca_file] ||= ca_file

    Faraday.new(options) do |b|
      b.use(CC::Service::ResponseCheck)
      b.request(:url_encoded)
      b.adapter(*Array(options[:adapter] || config[:adapter]))
    end
  end
end

#http_method(method, url = nil, body = nil, headers = nil) ⇒ Object



48
49
50
51
52
53
54
55
56
57
# File 'lib/cc/service/http.rb', line 48

def http_method(method, url = nil, body = nil, headers = nil)
  block = Proc.new if block_given?

  http.send(method) do |req|
    req.url(url)                if url
    req.headers.update(headers) if headers
    req.body = body             if body
    block.call req if block
  end
end

#raw_get(url = nil, params = nil, headers = nil) ⇒ Object



34
35
36
37
38
39
40
41
# File 'lib/cc/service/http.rb', line 34

def raw_get(url = nil, params = nil, headers = nil)
  http.get do |req|
    req.url(url)                if url
    req.params.update(params)   if params
    req.headers.update(headers) if headers
    yield req if block_given?
  end
end

#raw_post(url = nil, body = nil, headers = nil) ⇒ Object



43
44
45
46
# File 'lib/cc/service/http.rb', line 43

def raw_post(url = nil, body = nil, headers = nil)
  block = Proc.new if block_given?
  http_method :post, url, body, headers, &block
end

#service_get(url = nil, body = nil, headers = nil, &block) ⇒ Object



18
19
20
# File 'lib/cc/service/http.rb', line 18

def service_get(url = nil, body = nil, headers = nil, &block)
  raw_get(url, body, headers, &block)
end

#service_post(url, body = nil, headers = nil, &block) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
# File 'lib/cc/service/http.rb', line 22

def service_post(url, body = nil, headers = nil, &block)
  block ||= lambda{|*args| Hash.new }
  response = raw_post(url, body, headers)
  {
    ok: response.success?,
    params: body.as_json,
    endpoint_url: url,
    status: response.status,
    message: "Success"
  }.merge(block.call(response))
end