Class: DIDWW::ComplexObject::Base
- Inherits:
-
Object
- Object
- DIDWW::ComplexObject::Base
show all
- Defined in:
- lib/didww/complex_objects/base.rb
Class Method Summary
collapse
Instance Method Summary
collapse
Constructor Details
#initialize(params = {}) ⇒ Base
Returns a new instance of Base.
63
64
65
66
67
68
|
# File 'lib/didww/complex_objects/base.rb', line 63
def initialize(params = {})
params.each { |k, v| self[k] = v }
self.class.schema.each_property do |property|
attributes[property.name] = property.default unless attributes.has_key?(property.name) || property.default.nil?
end
end
|
Class Method Details
.cast(value, default) ⇒ Object
Type casting for JsonApiClient parser/setters
25
26
27
28
29
30
31
32
33
34
35
36
|
# File 'lib/didww/complex_objects/base.rb', line 25
def cast(value, default)
case value
when self
value
when Hash
cast_single_object(value)
when Array
value.map { |item| cast(item, item) }
else
default
end
end
|
.property(name, options = {}) ⇒ Object
14
15
16
17
18
|
# File 'lib/didww/complex_objects/base.rb', line 14
def property(name, options = {})
schema.add(name, options)
define_method(name.to_sym) { self[name] }
define_method("#{name}=".to_sym) { |val| self[name] = val }
end
|
.schema ⇒ Object
20
21
22
|
# File 'lib/didww/complex_objects/base.rb', line 20
def schema
@schema ||= JsonApiClient::Schema.new
end
|
.type ⇒ Object
Specifies the JSON API resource type. By default this is inferred from the resource class name.
10
11
12
|
# File 'lib/didww/complex_objects/base.rb', line 10
def type
name.demodulize.underscore.pluralize
end
|
Instance Method Details
#[](key) ⇒ Object
70
71
72
|
# File 'lib/didww/complex_objects/base.rb', line 70
def [](key)
attributes[key]
end
|
#[]=(key, value) ⇒ Object
74
75
76
77
|
# File 'lib/didww/complex_objects/base.rb', line 74
def []=(key, value)
property = self.class.schema.find(key)
attributes[key] = property ? property.cast(value) : value
end
|
#as_json ⇒ Object
When we represent this resource for serialization (create/update), we do so with this implementation
81
82
83
84
85
|
# File 'lib/didww/complex_objects/base.rb', line 81
def as_json(*)
{ type: type }.with_indifferent_access.tap do |h|
h[:attributes] = attributes.as_json
end
end
|
#as_json_api ⇒ Object
87
|
# File 'lib/didww/complex_objects/base.rb', line 87
def as_json_api(*); as_json end
|
#attributes ⇒ Object
59
60
61
|
# File 'lib/didww/complex_objects/base.rb', line 59
def attributes
@attributes ||= ActiveSupport::HashWithIndifferentAccess.new
end
|
#type ⇒ Object
55
56
57
|
# File 'lib/didww/complex_objects/base.rb', line 55
def type
self.class.type
end
|