module Proxima::Serialization

Public Class Methods

included(base) click to toggle source
# File lib/proxima/serialization.rb, line 135
def self.included base
  base.extend ClassMethods
end

Public Instance Methods

as_json(opts = {}) click to toggle source
# File lib/proxima/serialization.rb, line 41
def as_json(opts = {})
  hash = self.serializable_hash opts

  json = {}
  self.class.attributes.each do |attribute, params|
    next if (
      !opts.key?(:include_clean) && !send("#{attribute}_changed?") ||
      !opts.key?(:include_nil)   && hash[attribute.to_s] == nil
    )

    json_path = params[:json_path]
    value     = hash[attribute.to_s]

    next if value.nil?

    if params[:klass]
      begin
        value = Proxima.type_to_json params[:klass], value
      rescue Exception => e
        raise "Cannot convert value \"#{value}\" for attribute \"#{attribute}\" from type" +
          " #{params[:klass].name}: #{e.message}"
      end
    end

    if opts.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 opts.key? :root
    opts[: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, opts = {}) click to toggle source
# File lib/proxima/serialization.rb, line 6
def from_json(json, opts = {})
  json = ActiveSupport::JSON.decode(json) if json.is_a?(String)
  json = json.values.first if opts[:include_root] || self.include_root_in_json
  json = json.first        if opts[:single_model_from_array] && json.is_a?(Array)
  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 if value.nil?

    if params[:klass]
      begin
        value = Proxima.type_from_json params[:klass], value
      rescue Exception => e
        raise "Cannot convert value \"#{value}\" for attribute \"#{attribute}\" to type" +
          " #{params[:klass].name}: #{e.message}"
      end
    end

    hash[attribute] = value
  end

  self.attributes = hash
  self.new_record = opts[:new_record] if opts[:new_record] != nil
  self
end
to_h() click to toggle source
# File lib/proxima/serialization.rb, line 94
def to_h
  hash = {}
  self.class.attributes.each do |attribute, params|
    hash[attribute] = self.send attribute
  end
  hash
end