Class: Outbrain::Request

Inherits:
Config
  • Object
show all
Defined in:
lib/outbrain/request.rb

Constant Summary

Constants inherited from Config

Config::BASE

Class Method Summary collapse

Methods inherited from Config

api=, api_version=

Class Method Details

.all(resource, options = {}) ⇒ Object



26
27
28
# File 'lib/outbrain/request.rb', line 26

def self.all(resource, options={})
  where(resource, {}, options)
end

.create(resource, options = {}) ⇒ Object



45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/outbrain/request.rb', line 45

def self.create(resource, options={})
  attributes = options.fetch(:attributes, {})

  response = api.post("/amplify/#{api_version}/#{resource}", attributes.to_json)
  json_body = JSON.parse(response.body)

  if response.status == 200
    options[:as].new(json_body)
  else
    a = options[:as].new
    a.errors.push(json_body)
    a
  end
end

.find(resource_path, id, options = {}) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/outbrain/request.rb', line 30

def self.find(resource_path, id, options={})
  response = api.get("/amplify/#{api_version}/#{resource_path}/#{id}")
  json_body = JSON.parse(response.body)

  fail InvalidOption 'requires an as option' unless options[:as]

  if response.status == 200
    options[:as].new(json_body)
  else
    a = options[:as].new
    a.errors.push(json_body)
    a
  end
end

.update(resource_path, id, options = {}) ⇒ Object



60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/outbrain/request.rb', line 60

def self.update(resource_path, id, options={})
  attributes = options.fetch(:attributes, {})
  response = api.put("/amplify/#{api_version}/#{resource_path}/#{id}", attributes.to_json)
  json_body = JSON.parse(response.body)

  if response.status == 200
    options[:as].new(json_body)
  else
    a = options[:as].new
    a.errors.push(json_body)
    a
  end
end

.where(resource_path, query = {}, options = {}) ⇒ Object



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/outbrain/request.rb', line 3

def self.where(resource_path, query={}, options={})
  request_path = "/amplify/#{api_version}/#{resource_path}"
  query_string = query.map{|k,v| "#{k}=#{v}"}.join("&")
  request_path = request_path + '?' + query_string unless query_string.empty?
  response = api.get(request_path)
  resource_name = options.fetch(:resource_name, resource_path)
  meta_requests = options.fetch(:meta_resource_names)
  json_body = JSON.parse(response.body) # catch and raise proper api error

  fail InvalidOption 'requires an as option' unless options[:as]

  if response.status == 200
    Outbrain::Api::Relation.new.tap do |r|
      meta_requests.each{ |field| r.send("#{field}=", json_body[field]) }
      r.relations = json_body[resource_name].map{ |obj| options[:as].new(obj) }
    end
  else
    Outbrain::Api::Relation.new.tap do |r|
      r.errors << json_body
    end
  end
end