This repository has been archived by the owner on May 8, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy pathapi.rb
81 lines (66 loc) · 1.87 KB
/
api.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
require 'net/http'
require 'json'
class Api
class Error < RuntimeError; end
class <<self
def port
@port
end
def port=(port)
@port = port.to_i
end
def profile
response = post '/eval', :script => '(require "io/Dir").profile.path',
:type => 'text/coffeescript'
JSON.parse(response.body)['result']
end
def get(path)
request :method => :get,
:path => path
end
def post(path, data=nil)
request :method => :post,
:path => path,
:body => data
end
def put(path, data=nil)
request :method => :put,
:path => path,
:body => data
end
def json(method, path, data=nil)
JSON.parse(request(:method => method, :path => path, :body => data).body)
end
def request(options={})
Net::HTTP.start('127.0.0.1', port) do |http|
request = Net::HTTP.const_get(options[:method].to_s.capitalize).new options[:path]
request['Accept'] = 'application/json'
case options[:body]
when String
request.body = options[:body]
request.content_type = options[:content_type] || 'text/plain'
when nil
# no body
else
request.body = options[:body].to_json
request.content_type = 'application/json'
end
case response = http.request(request)
when Net::HTTPSuccess
return response
end
raise Error, "Invalid response: #{response.inspect}: #{response.body}"
end
end
def [](action, body=nil)
response = post '/_legacy', :action => action, :body => body
res = JSON.parse(response.body)['response']
case res['status']
when 'ok'
return res[action]
when 'error'
raise Error, res['error']
end
end
end
end