class Paggi::Resource
Attributes
created[RW]
errors[RW]
id[RW]
Public Class Methods
build(data, error = nil)
click to toggle source
# 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()
click to toggle source
# File lib/paggi/resource.rb, line 9 def class_name self.name.split('::')[-1] end
new(attributes = {})
click to toggle source
# File lib/paggi/resource.rb, line 64 def initialize(attributes = {}) attributes.each{ |name, value| self.instance_variable_set("@#{name}", value) } self.errors = [] end
opts(headers={})
click to toggle source
# File lib/paggi/resource.rb, line 17 def opts(headers={}) { basic_auth: {username: Paggi.configuration.api_key, password: ''}, headers: headers.merge({"Content-Type" => 'application/json'}) } end
request(path=nil, params={}, method=:GET, header={})
click to toggle source
# File lib/paggi/resource.rb, line 36 def request(path=nil, params={}, method=:GET, header={}) options = opts(header).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
url()
click to toggle source
# File lib/paggi/resource.rb, line 13 def url "#{Paggi.configuration.host}/api/#{Paggi.configuration.version}/#{Paggi::Util.underscore(class_name)}s" end
Public Instance Methods
to_json(attrs = [:id, :created])
click to toggle source
# 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?()
click to toggle source
# File lib/paggi/resource.rb, line 69 def valid? self.errors.empty? end