Module: Proxima::Serialization
- Included in:
- Model
- Defined in:
- lib/proxima/serialization.rb
Defined Under Namespace
Modules: ClassMethods
Class Method Summary collapse
Instance Method Summary collapse
- #as_json(options = {}) ⇒ Object
- #from_json(json, include_root = self.include_root_in_json) ⇒ Object
- #to_h ⇒ Object
Class Method Details
.included(base) ⇒ Object
113 114 115 |
# File 'lib/proxima/serialization.rb', line 113 def self.included base base.extend ClassMethods end |
Instance Method Details
#as_json(options = {}) ⇒ Object
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 |
# File 'lib/proxima/serialization.rb', line 34 def as_json( = {}) hash = serializable_hash json = {} self.class.attributes.each do |attribute, params| next if ( !.key?(:include_clean) && !send("#{attribute}_changed?") || !.key?(:include_nil) && hash[attribute.to_s] == nil ) json_path = params[:json_path] value = hash[attribute.to_s] value = value.as_json if value.respond_to? :as_json if .key? :flatten json[json_path] = value next end json_path_chunks = json_path.split '.' last_json_path_chunk = json_path_chunks.pop json_ctx = json for json_path_chunk in json_path_chunks json_ctx[json_path_chunk] = {} unless json_ctx[json_path_chunk].is_a?(Hash) json_ctx = json_ctx[json_path_chunk] end json_ctx[last_json_path_chunk] = value end root = if .key? :root [:root] else self.include_root_in_json end if root root = self.class.model_name.element if root == true { root => json } else json end end |
#from_json(json, include_root = self.include_root_in_json) ⇒ Object
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
# File 'lib/proxima/serialization.rb', line 6 def from_json(json, include_root = self.include_root_in_json) json = ActiveSupport::JSON.decode(json) if json.is_a?(String) json = json.values.first if include_root hash = {} self.class.attributes.each do |attribute, params| json_path = params[:json_path] json_path_chunks = json_path.split '.' json_ctx = json for json_path_chunk in json_path_chunks json_ctx = json_ctx[json_path_chunk] break if json_ctx.nil? end value = json_ctx next unless value if params[:klass] && params[:klass].respond_to?(:from_json) value = params[:klass].from_json(value) end hash[attribute] = value end self.attributes = hash self end |
#to_h ⇒ Object
76 77 78 79 80 81 82 |
# File 'lib/proxima/serialization.rb', line 76 def to_h hash = {} self.class.attributes.each do |attribute, params| hash[attribute] = self.send attribute end hash end |