Class: Outbrain::Request

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

Class Method Summary collapse

Methods inherited from Config

api=, api_version=

Class Method Details

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



21
22
23
# File 'lib/outbrain/request.rb', line 21

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

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



40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/outbrain/request.rb', line 40

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

  response = api.post("#{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



25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/outbrain/request.rb', line 25

def self.find(resource_path, id, options={})
  response = api.get("#{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



55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/outbrain/request.rb', line 55

def self.update(resource_path, id, options={})
  attributes = options.fetch(:attributes, {})
  wrap_response = options.fetch(:wrap_response, true)
  response = api.put("#{resource_path}/#{id}", attributes.to_json)
  success = (response.status == 200)
  return success  unless wrap_response
  json_body = JSON.parse(response.body)
  if success
    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
# File 'lib/outbrain/request.rb', line 3

def self.where(resource_path, query={}, options={})
  request_path = 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)
  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(json_body.merge(relation_class: options[:as], relation_name: resource_name))
  else
    Outbrain::Api::Relation.new(errors: json_body)
  end
end