class DIDWW::ComplexObject::Base
Public Class Methods
cast(value, default)
click to toggle source
Type casting for JsonApiClient parser/setters
# File lib/didww/complex_objects/base.rb, line 24 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
new(params = {})
click to toggle source
# File lib/didww/complex_objects/base.rb, line 59 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
property(name, options = {})
click to toggle source
# File lib/didww/complex_objects/base.rb, line 13 def property(name, options = {}) property = schema.add(name, options) define_method(name.to_sym) { self[name] } define_method("#{name}=".to_sym) { |val| self[name] = val } end
schema()
click to toggle source
# File lib/didww/complex_objects/base.rb, line 19 def schema @schema ||= JsonApiClient::Schema.new end
type()
click to toggle source
Specifies the JSON API resource type. By default this is inferred from the resource class name.
# File lib/didww/complex_objects/base.rb, line 9 def type name.demodulize.underscore.pluralize end
Protected Class Methods
cast_single_object(hash)
click to toggle source
# File lib/didww/complex_objects/base.rb, line 39 def cast_single_object(hash) hash = hash.with_indifferent_access klass = class_for_type(hash[:type]) klass ? klass.new(hash[:attributes] || {}) : hash end
class_for_type(type)
click to toggle source
Returns a ComplexObject
class if given JSON API type matches any
# File lib/didww/complex_objects/base.rb, line 46 def class_for_type(type) "#{parent.name}::#{type.classify}".safe_constantize end
Public Instance Methods
[](key)
click to toggle source
# File lib/didww/complex_objects/base.rb, line 66 def [](key) attributes[key] end
[]=(key, value)
click to toggle source
# File lib/didww/complex_objects/base.rb, line 70 def []=(key, value) property = self.class.schema.find(key) attributes[key] = property ? property.cast(value) : value end
as_json(*)
click to toggle source
When we represent this resource for serialization (create/update), we do so with this implementation
# File lib/didww/complex_objects/base.rb, line 77 def as_json(*) { type: type }.with_indifferent_access.tap do |h| h[:attributes] = attributes.as_json end end
as_json_api(*)
click to toggle source
# File lib/didww/complex_objects/base.rb, line 83 def as_json_api(*); as_json end
attributes()
click to toggle source
# File lib/didww/complex_objects/base.rb, line 55 def attributes @attributes ||= ActiveSupport::HashWithIndifferentAccess.new end
type()
click to toggle source
# File lib/didww/complex_objects/base.rb, line 51 def type self.class.type end