Class: Courier::CourierAPISession

Inherits:
Object
  • Object
show all
Defined in:
lib/trycourier/session.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(base_url) ⇒ CourierAPISession

Returns a new instance of CourierAPISession.



7
8
9
# File 'lib/trycourier/session.rb', line 7

def initialize(base_url)
  @base_url = base_url
end

Instance Attribute Details

#base_urlObject (readonly)

getter for base url (for testing)



78
79
80
# File 'lib/trycourier/session.rb', line 78

def base_url
  @base_url
end

Instance Method Details

#init_basic_auth(username, password) ⇒ Object



16
17
18
19
20
# File 'lib/trycourier/session.rb', line 16

def init_basic_auth(username, password)
  @username = username
  @password = password
  @auth_method = "basic"
end

#init_token_auth(auth_token) ⇒ Object



11
12
13
14
# File 'lib/trycourier/session.rb', line 11

def init_token_auth(auth_token)
  @auth_token = "Bearer #{auth_token}"
  @auth_method = "token"
end

#is_authenticatedObject



69
70
71
72
73
74
75
# File 'lib/trycourier/session.rb', line 69

def is_authenticated
  if !@auth_method.nil?
    true
  else
    false
  end
end

#send(path, method, params: nil, body: nil, headers: nil) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/trycourier/session.rb', line 22

def send(path, method, params: nil, body: nil, headers: nil)
  uri = URI.parse(@base_url + path.to_s)
  if params
    uri.query = URI.encode_www_form(params)
  end
  http = Net::HTTP.new(uri.host, uri.port)
  http.use_ssl = true
  http.verify_mode = OpenSSL::SSL::VERIFY_PEER

  req = case method
  when "GET"
    Net::HTTP::Get.new(uri)
  when "POST"
    Net::HTTP::Post.new(uri)
  when "PUT"
    Net::HTTP::Put.new(uri)
  when "PATCH"
    Net::HTTP::Patch.new(uri)
  when "DELETE"
    Net::HTTP::Delete.new(uri)
  else
    Net::HTTP::Get.new(uri)
  end

  case @auth_method
  when "token"
    req["authorization"] = @auth_token
  when "basic"
    req.basic_auth @username, @password
  end

  req["content-type"] = "application/json"
  req["User-Agent"] = "courier-ruby/#{Courier::VERSION}"

  if body
    req.body = body.to_json
  end

  if headers
    headers.each do |k, v|
      req.add_field(k.to_s, v.to_s)
    end
  end

  http.request(req)
end