Module: Ahub::APIHelpers

Included in:
Answer, Group, Question, Space, Topic, User
Defined in:
lib/ahub/modules/api_helpers.rb

Instance Method Summary collapse

Instance Method Details

#admin_headersObject



15
16
17
# File 'lib/ahub/modules/api_helpers.rb', line 15

def admin_headers
  headers(username: Ahub::ADMIN_USER, password: Ahub::ADMIN_PASS)
end

#base_urlObject



39
40
41
42
# File 'lib/ahub/modules/api_helpers.rb', line 39

def base_url
  class_name = name.gsub(/Ahub::/, '').downcase
  "#{Ahub::DOMAIN}/services/v2/#{class_name}"
end

#find(id) ⇒ Object



19
20
21
22
23
24
25
# File 'lib/ahub/modules/api_helpers.rb', line 19

def find(id)
  url = "#{base_url}/#{id}.json"

  new JSON.parse(RestClient.get(url, admin_headers), symbolize_names:true)
rescue RestClient::ResourceNotFound => e
  nil
end

#find_all(params: nil, page: 1, pageSize: 30) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
# File 'lib/ahub/modules/api_helpers.rb', line 27

def find_all(params: nil, page: 1, pageSize: 30)
  url = "#{base_url}.json?page=#{page}&pageSize=#{pageSize}"

  if params
    params.each{|k,v| url << "&#{k}=#{URI.encode(v)}"}
  end

  JSON.parse(RestClient.get(url, admin_headers), symbolize_names:true)[:list].map do |node|
    new(node)
  end
end

#headers(username: 'answerhub', password: 'answerhub') ⇒ Object



5
6
7
8
9
10
11
12
13
# File 'lib/ahub/modules/api_helpers.rb', line 5

def headers(username:'answerhub', password:'answerhub')
  encoded = "Basic #{::Base64.strict_encode64("#{username}:#{password}")}"

  {
    'Authorization' => encoded,
    'Accept' => "application/json",
    'Content-type' => "application/json",
  }
end

#object_id_from_response(response) ⇒ Object



44
45
46
# File 'lib/ahub/modules/api_helpers.rb', line 44

def object_id_from_response(response)
  response.headers[:location].match(/(?<id>\d*)\.json/)[:id].to_i
end