Module: JSONtoDB::REST

Defined in:
lib/jsontodb/rest.rb

Overview

This module handles REST requests

Class Method Summary collapse

Class Method Details

.basic_request(klass, url, user, pass) ⇒ Object



50
51
52
53
54
55
# File 'lib/jsontodb/rest.rb', line 50

def basic_request(klass, url, user, pass)
  uri = URI(url)
  request = klass.new(uri)
  request.basic_auth(user, pass)
  request
end

.data_request(klass, url, src, user, pass) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
# File 'lib/jsontodb/rest.rb', line 30

def data_request(klass, url, src, user, pass)
  if File.directory?(src)

    Dir["#{src}/*.json"].each do |file|
      file_request(klass, url, file, user, pass)
    end

  elsif File.file?(src)
    file_request(klass, url, src, user, pass)
  end
end

.delete(url, user, pass) ⇒ Object



12
13
14
# File 'lib/jsontodb/rest.rb', line 12

def delete(url, user, pass)
  no_data_request(Net::HTTP::Delete, url, user, pass)
end

.file_request(klass, url, src, user, pass) ⇒ Object



42
43
44
45
46
47
48
# File 'lib/jsontodb/rest.rb', line 42

def file_request(klass, url, src, user, pass)
  request = basic_request(klass, url, user, pass)
  request.content_type = 'application/json'
  request.set_form_data(JSONtoDB::IO.read(src))

  make_request(url, request)
end

.get(url, user, pass) ⇒ Object



8
9
10
# File 'lib/jsontodb/rest.rb', line 8

def get(url, user, pass)
  no_data_request(Net::HTTP::Get, url, user, pass)
end

.handle_errors(response) ⇒ Object



67
68
69
70
71
72
# File 'lib/jsontodb/rest.rb', line 67

def handle_errors(response)
  return response.body if response.code.start_with?('20')

  puts "ERROR: '#{response.code}' response. (#{response.message} - #{response.class.name})"
  ''
end

.make_request(url, request) ⇒ Object



57
58
59
60
61
62
63
64
65
# File 'lib/jsontodb/rest.rb', line 57

def make_request(url, request)
  uri = URI(url)

  response = Net::HTTP.start(uri.hostname, uri.port) do |http|
    http.request(request)
  end

  handle_errors(response)
end

.no_data_request(klass, url, user, pass) ⇒ Object



16
17
18
19
20
# File 'lib/jsontodb/rest.rb', line 16

def no_data_request(klass, url, user, pass)
  request = basic_request(klass, url, user, pass)

  make_request(url, request)
end

.post(url, src, user, pass) ⇒ Object



26
27
28
# File 'lib/jsontodb/rest.rb', line 26

def post(url, src, user, pass)
  data_request(Net::HTTP::Post, url, src, user, pass)
end

.put(url, src, user, pass) ⇒ Object



22
23
24
# File 'lib/jsontodb/rest.rb', line 22

def put(url, src, user, pass)
  data_request(Net::HTTP::Put, url, src, user, pass)
end