Class: Parse::HttpClient

Inherits:
Object
  • Object
show all
Defined in:
lib/parse/http_client.rb

Direct Known Subclasses

BatchHttpClient

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(host) ⇒ HttpClient

Returns a new instance of HttpClient.



6
7
8
9
# File 'lib/parse/http_client.rb', line 6

def initialize host
  @host = host
  @dry_run = false
end

Instance Attribute Details

#dry_runObject

Returns the value of attribute dry_run.



4
5
6
# File 'lib/parse/http_client.rb', line 4

def dry_run
  @dry_run
end

#hostObject

Returns the value of attribute host.



4
5
6
# File 'lib/parse/http_client.rb', line 4

def host
  @host
end

Instance Method Details

#dry_run!Object



15
16
17
# File 'lib/parse/http_client.rb', line 15

def dry_run!
  @dry_run = true
end

#dry_run?Boolean

Returns:

  • (Boolean)


11
12
13
# File 'lib/parse/http_client.rb', line 11

def dry_run?
  !!@dry_run
end

#request(method, endpoint, headers = {}, body = nil, &block) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/parse/http_client.rb', line 19

def request method, endpoint, headers={}, body=nil, &block
  if dry_run
    $stderr.puts "#{
      method} #{endpoint}\n#{
      headers.to_a.map{|k,v| "#{k}: #{v}"}.join "\n"
      }\n\n#{
      body}"
    block.call({}) if block
    return
  end

  req = eval("Net::HTTP::#{method.to_s.capitalize}").new endpoint, headers
  req.body = body if body
  client = Net::HTTP.new @host, 443
  client.set_debug_output $stderr if $DEBUG
  client.use_ssl = true
  client.start do
    # TODO
    resp = client.request req
    resp_body = resp.body.empty? ? nil : JSON.parse(resp.body)
    raise StandardError.new "error calling #{endpoint}: #{
      resp_body['error']}" if resp_body.is_a?(Hash) && resp_body.has_key?('error')
    block.call resp_body if block
  end
end