Class: Paggi::Resource
- Inherits:
-
Object
show all
- Includes:
- HTTParty
- Defined in:
- lib/paggi/resource.rb
Instance Attribute Summary collapse
Class Method Summary
collapse
Instance Method Summary
collapse
Constructor Details
#initialize(attributes = {}) ⇒ Resource
Returns a new instance of Resource.
64
65
66
67
|
# File 'lib/paggi/resource.rb', line 64
def initialize(attributes = {})
attributes.each{ |name, value| self.instance_variable_set("@#{name}", value) }
self.errors = []
end
|
Instance Attribute Details
#created ⇒ Object
Returns the value of attribute created.
5
6
7
|
# File 'lib/paggi/resource.rb', line 5
def created
@created
end
|
#errors ⇒ Object
Returns the value of attribute errors.
5
6
7
|
# File 'lib/paggi/resource.rb', line 5
def errors
@errors
end
|
#id ⇒ Object
Returns the value of attribute id.
5
6
7
|
# File 'lib/paggi/resource.rb', line 5
def id
@id
end
|
Class Method Details
.build(data, error = nil) ⇒ Object
24
25
26
27
28
29
30
31
32
33
34
|
# File 'lib/paggi/resource.rb', line 24
def build(data, error = nil)
if data['result'] && data['total']
instance = Paggi::Paginated.new()
instance.result = data['result'].map { |element| self.new(element) }
instance.total = data['total']
else
instance = self.new(data)
end
instance.errors = error.errors unless error.nil?
instance
end
|
.class_name ⇒ Object
9
10
11
|
# File 'lib/paggi/resource.rb', line 9
def class_name
self.name.split('::')[-1]
end
|
.opts(headers = {}) ⇒ Object
17
18
19
20
21
22
|
# File 'lib/paggi/resource.rb', line 17
def opts(={})
{
basic_auth: {username: Paggi.configuration.api_key, password: ''},
headers: .merge({"Content-Type" => 'application/json'})
}
end
|
.request(path = nil, params = {}, method = :GET, header = {}) ⇒ Object
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
|
# File 'lib/paggi/resource.rb', line 36
def request(path=nil, params={}, method=:GET, ={})
options = opts().merge(body: JSON.generate(params))
url_abs = path.nil? ? url : "#{url}/#{path}"
response = case method
when :GET
get(url_abs, options)
when :POST
post(url_abs, options)
when :PUT
put(url_abs, options)
else
raise StandardError.new("Method #{method} not implemented")
end
case response.code
when 200, 402
build(JSON.parse(response.body))
when 422, 404
result = JSON.parse(response.body)
PaggiError.new(result)
else
raise StandardError.new(response.message)
end
end
|
Instance Method Details
#to_json(attrs = [:id, :created]) ⇒ Object
73
74
75
76
77
78
79
80
|
# File 'lib/paggi/resource.rb', line 73
def to_json(attrs = [:id, :created])
result = {}
attrs.each{ |attr|
value = self.instance_variable_get("@#{attr}")
result[attr] = value unless value.nil? or value.empty?
}
result
end
|
#valid? ⇒ Boolean
69
70
71
|
# File 'lib/paggi/resource.rb', line 69
def valid?
self.errors.empty?
end
|