Class: Twoffein::HTTP

Inherits:
Object
  • Object
show all
Defined in:
lib/twoffein-client/http.rb

Class Method Summary collapse

Class Method Details

.create_url(path, params = {}) ⇒ Object



11
12
13
14
15
# File 'lib/twoffein-client/http.rb', line 11

def self.create_url(path, params={})
  query = URI.encode_www_form(params)
  # TODO: Change API-URI: Add controller in MVC –> rest_client (https://github.com/adamwiggins/rest-client)
  URI.join(BASE_URL, path+'/').to_s + '?' + query
end

.fetch(uri_str, limit = 10) ⇒ Object

Raises:

  • (ArgumentError)


17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/twoffein-client/http.rb', line 17

def self.fetch(uri_str, limit = 10)
  # You should choose a better exception.
  raise ArgumentError, 'too many HTTP redirects' if limit == 0

  response = Net::HTTP.get_response(URI(uri_str))

  case response
  when Net::HTTPSuccess then
    response
  when Net::HTTPRedirection then
    location = response['location']
    #warn "redirected to #{location}"
    fetch(location, limit - 1)
  else
    response.value
  end
end

.get(path, params = {}) ⇒ Object



74
75
76
# File 'lib/twoffein-client/http.rb', line 74

def self.get(path, params={})
  request(:get, path, params)
end

.post(path, params = {}) ⇒ Object



78
79
80
# File 'lib/twoffein-client/http.rb', line 78

def self.post(path, params={})
  request(:post, path, params)
end

.post_data(path, data, params = {}) ⇒ Object



54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/twoffein-client/http.rb', line 54

def self.post_data(path, data, params={})
  #self.request(:post, path, params)
  uri = URI(path)
  req = Net::HTTP::Post.new(uri.path)
  req.set_form_data(data)
  #req.body = multipart_data
  #req.content_type = 'multipart/form-data'

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

  case res
  when Net::HTTPSuccess, Net::HTTPRedirection
    # OK
  else
    raise res.value
  end
end

.request(verb, path, params = {}) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/twoffein-client/http.rb', line 35

def self.request(verb, path, params={})
  Util.compact! params
  case verb
  when :get
    res = fetch(create_url([verb, path].join('/'), PARAMS.merge(params)))
    case content_type(res)
    when /xml/
      puts "XML isn't supported."
      exit 1
      #xml = REXML::Document.new(res.body)
    when /json/
      return JSON.parse(res.body, :symbolize_names => true)
    end
  when :post # TODO
    res = fetch(create_url([:post, path].join('/'), PARAMS.merge(params)))
  end
  JSON.parse(res.body, :symbolize_names => true)
end