Class: Bolster::Server

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

Instance Method Summary collapse

Constructor Details

#initialize(host, port, options = {}) ⇒ Server

Returns a new instance of Server.



6
7
8
9
10
# File 'lib/bolster.rb', line 6

def initialize(host, port, options = {})
    @host = host
    @port = port
    @options = options
end

Instance Method Details

#delete(uri) ⇒ Object



12
13
14
15
# File 'lib/bolster.rb', line 12

def delete(uri)
    res = request(Net::HTTP::Delete.new(uri))
    res.body
end

#get(uri) ⇒ Object



17
18
19
20
# File 'lib/bolster.rb', line 17

def get(uri)
    res = request(Net::HTTP::Get.new(uri))
    res.body
end

#handle_error(req, res) ⇒ Object



48
49
50
51
52
53
54
# File 'lib/bolster.rb', line 48

def handle_error(req, res)
    e = RuntimeError.new(%Q{#{res.code}: #{res.message}
        METHOD: #{req.method}
        URI: #{req.path}
        #{req.body}})
    raise e
end

#post(uri, json) ⇒ Object



29
30
31
32
33
34
# File 'lib/bolster.rb', line 29

def post(uri, json)
    req = Net::HTTP::Post.new(uri)
    req['content-type'] = 'application/json'
    req.body = json
    request(req)
end

#put(uri, json) ⇒ Object



22
23
24
25
26
27
# File 'lib/bolster.rb', line 22

def put(uri, json)
    req = Net::HTTP::Put.new(uri)
    req['content-type'] = 'application/json'
    req.body = json
    request(req)
end

#request(req) ⇒ Object



36
37
38
39
40
41
42
43
44
45
46
# File 'lib/bolster.rb', line 36

def request(req)
    if @options.has_key?(:user) && @options.has_key?(:password)
        req.basic_auth(@options[:user], @options[:password])
    end
    
    res = Net::HTTP.start(@host, @port) { |http| http.request(req) }
    unless res.kind_of?(Net::HTTPSuccess)
        handle_error(req, res)
    end
    res
end