Method: EPlat::Concerns::OverwriteInstanceMethods#as_json

Defined in:
lib/e_plat/resource/concerns/overwrite_instance_methods.rb

#as_json(options = {}) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/e_plat/resource/concerns/overwrite_instance_methods.rb', line 14

def as_json(options = {})
	full_json = super(options)
	return {} if read_only?

	if mapping.class.virtual_collections.present?
		virtual_keys = mapping.class.virtual_collections.map{|c| c[:name]}.map(&:to_s)
		
		full_json.reject!{|key, value| virtual_keys.include?(key) } # not needed in JSON, as it's just a proxy for setting the real attributes
	end

	return full_json if new_record? # new records request with all attributes
	
	request_json = 
		if include_root_in_json or options[:root].present?
			{ element_name => select_changed_attributes_and_collection_keys(full_json[element_name]) }
		else
			select_changed_attributes_and_collection_keys(full_json)
		end

	if top_level_resource? # then check that any present collections have all entries represented with atleast an ID, so they're not removed
		hash_without_root(request_json).each do |key, value|
			next unless arrayOfPresentHashes?(value)

			hash_without_root(request_json)[key].filter!(&:present?)
			hash_without_root(request_json)[key] += unrepresented_collection_ids(key, value).map{ |id| { "id" => id } }
		end
	end

		add_root_if_needed(request_json, options[:root]).reject do |k,v| 
		if v.is_a?(Array) 
			v.reject(&:empty?).empty?
		else 
			v.nil? || v.blank?
		end
	end
end