Class: Kounta::Resource
- Inherits:
-
Hashie::Dash
- Object
- Hashie::Dash
- Kounta::Resource
show all
- Includes:
- Hashie::Extensions::Coercion
- Defined in:
- lib/kounta/resource.rb
Direct Known Subclasses
Address, Category, Company, Customer, Inventory, Line, Order, Payment, Person, PriceList, Product, Site, Tax
Class Method Summary
collapse
Instance Method Summary
collapse
Constructor Details
#initialize(hash = {}) ⇒ Resource
Returns a new instance of Resource.
37
38
39
40
41
42
43
44
45
46
47
|
# File 'lib/kounta/resource.rb', line 37
def initialize(hash={})
if hash
hash.each_pair do |k,v|
begin
self[k] = v
rescue NoMethodError => e
raise Kounta::Errors::UnknownResourceAttribute.new("Unknown attribute: #{k} on resource #{self.class}")
end
end
end
end
|
Class Method Details
.coerce(data) ⇒ Object
13
14
15
16
17
18
19
|
# File 'lib/kounta/resource.rb', line 13
def self.coerce(data)
if data.kind_of? Array
data.map { |item| self.new(item) }
else
self.new(data)
end
end
|
.has_many(sym, klass, assignments, route) ⇒ Object
31
32
33
34
35
|
# File 'lib/kounta/resource.rb', line 31
def self.has_many(sym, klass, assignments, route)
define_method(sym) do |*args|
client.objects_from_response(klass, :get, route.call(self), {:params => args[0]}).map {|returned_klass| assign_into(returned_klass, self, assignments) }
end
end
|
.has_one(sym, klass, assignments, route) ⇒ Object
21
22
23
24
25
26
27
28
29
|
# File 'lib/kounta/resource.rb', line 21
def self.has_one(sym, klass, assignments, route)
define_method(sym) do |item_id=nil, *args|
if item_id
assign_into(client.object_from_response(klass, :get, route.call(self, item_id), {:params => args[0]}), self, assignments)
else
assign_into(klass.new, self, assignments)
end
end
end
|
Instance Method Details
#client ⇒ Object
49
50
51
|
# File 'lib/kounta/resource.rb', line 49
def client
@@client ||= Kounta::REST::Client.new
end
|
#ignored_properties(array = []) ⇒ Object
74
75
76
|
# File 'lib/kounta/resource.rb', line 74
def ignored_properties(array=[])
array + [:created_at, :updated_at, :id, :company_id]
end
|
#new? ⇒ Boolean
70
71
72
|
# File 'lib/kounta/resource.rb', line 70
def new?
!id
end
|
#save! ⇒ Object
62
63
64
65
66
67
68
|
# File 'lib/kounta/resource.rb', line 62
def save!
response = new? ? client.perform(resource_path, :post, {:body => to_hash}) : client.perform(resource_path, :put, {:body => to_hash})
response.parsed.each_pair do |k,v|
self[k] = v
end
self
end
|
#to_hash(hash = {}) ⇒ Object
53
54
55
56
57
58
59
60
|
# File 'lib/kounta/resource.rb', line 53
def to_hash(hash={})
{}.tap do |returning|
self.class.properties.each do |property|
next if ignored_properties.include?(property)
returning[property] = self[property] if self[property]
end
end.merge(hash)
end
|