Class: Switchcoder::Code

Inherits:
Object
  • Object
show all
Defined in:
lib/switchcoder/code.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(id, phone_number = nil, opts = nil) ⇒ Code

Returns a new instance of Code.



11
12
13
14
15
# File 'lib/switchcoder/code.rb', line 11

def initialize(id, phone_number = nil, opts = nil)
    @id = id;
    @phone_number = phone_number;
    @opts = opts;
end

Instance Attribute Details

#clientObject

Returns the value of attribute client.



8
9
10
# File 'lib/switchcoder/code.rb', line 8

def client
  @client
end

#idObject (readonly)

Returns the value of attribute id.



9
10
11
# File 'lib/switchcoder/code.rb', line 9

def id
  @id
end

#optsObject (readonly)

Returns the value of attribute opts.



9
10
11
# File 'lib/switchcoder/code.rb', line 9

def opts
  @opts
end

#phone_numberObject (readonly)

Returns the value of attribute phone_number.



9
10
11
# File 'lib/switchcoder/code.rb', line 9

def phone_number
  @phone_number
end

Instance Method Details

#invoke(query_parameters = {}, body = "", query_headers = nil) ⇒ Object

This method returns a Net::HTTPResponse object.

If called with a block, yields each fragment of the entity body in turn as a string as it is read from the socket. Note that in this case, the returned response object will not contain a (meaningful) body.



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
# File 'lib/switchcoder/code.rb', line 23

def invoke(query_parameters = {}, body = "", query_headers = nil)
  query_parameters ||= {}
  body ||= ""

  headers = {'Content-Type' => 'application/json', 'api_token' => client.api_token.to_s}
  headers["phone_number"] = @phone_number.number.to_s if @phone_number

  # add user headers to common headers
  headers.merge!( query_headers ) if query_headers


  uri = URI("https://#{client.host}/code/#{@id}/invoke")
  uri.query = URI.encode_www_form(query_parameters)

  http = Net::HTTP.new( uri.host, uri.port )
  http.use_ssl = (uri.scheme == 'https')
  
  res = http.start do |http|
    if client.opts[:method].to_s.downcase == 'get'
      http.get(uri.request_uri, headers) { |str| yield str if block_given? }
    else
      headers['Content-Length'] = body.length.to_s
      http.post(uri.request_uri, body, headers)  { |str| yield str if block_given? }
    end
  end

  return res
end