class JSONApi::ParamsDeserializer
Public Class Methods
deserialize(data, **options)
click to toggle source
# File lib/json_api/params_deserializer.rb, line 3 def self.deserialize(data, **options) self.new.deserialize(data, **options) end
Public Instance Methods
deserialize(data, **options)
click to toggle source
# File lib/json_api/params_deserializer.rb, line 7 def deserialize(data, **options) type = sanitize_type_name(data.fetch('type')) attributes = sanitize_hash(data.fetch('attributes', {})) relationships = data.fetch('relationships', {}) attributes['id'] = data['id'] unless data['id'].nil? deserialize_relationships(relationships, attributes) if options[:root] == false attributes else { type => attributes } end end
Private Instance Methods
deserialize_relationships(relationships, attributes)
click to toggle source
# File lib/json_api/params_deserializer.rb, line 26 def deserialize_relationships(relationships, attributes) relationships.each do |name, data| data = data['data'] name = sanitize_attribute_name(name) if data.is_a? Array attributes["#{name.singularize}_ids"] = data.map { |r| r.fetch('id') } elsif data attributes["#{name}_id"] = data.fetch('id') attributes["#{name}_type"] = sanitize_type_name(data.fetch('type')).classify else attributes["#{name}_id"] = nil end end end
sanitize_attribute_name(attribute_name)
click to toggle source
# File lib/json_api/params_deserializer.rb, line 49 def sanitize_attribute_name(attribute_name) attribute_name .downcase .underscore end
sanitize_hash(hash)
click to toggle source
# File lib/json_api/params_deserializer.rb, line 42 def sanitize_hash(hash) hash.map do |key, value| value = sanitize_hash(value) if value.is_a?(Hash) [sanitize_attribute_name(key), value] end.to_h end
sanitize_type_name(type_name)
click to toggle source
# File lib/json_api/params_deserializer.rb, line 55 def sanitize_type_name(type_name) sanitize_attribute_name(type_name) .singularize end