module OnappMarket::API::Serialize

Serialize and Deserialize of OnappMarket classes

Public Instance Methods

from_hash(hash) click to toggle source

De-serialize from a hash of values and create an instance

Attributes

  • hash - Hash of values

Returns

Object

# File lib/onapp_market/api/serialize.rb, line 265
def from_hash(hash)
  return nil unless hash[:type] || hash['type']
  # Instantiate class
  klass = Classes.get(hash[:type]) if hash[:type]
  klass = Classes.get(hash['type']) if hash['type']
  return nil if klass == nil
  klass.new hash
end
from_json(json) click to toggle source

De-serialize and create an instance of a class

Attributes

  • json Raw json

Returns

Object

# File lib/onapp_market/api/serialize.rb, line 279
def from_json(json)
  # Parse the JSON
  hash = JSON.parse(json, {:symbolize_names => true})
  OnappMarket::API::Serialize.from_hash(hash)
end
to_hash(item, role = :none) click to toggle source

Serialize a class to a hash and include it's type for de-serializing later

  • item - Item to serialize

Returns

Hash

# File lib/onapp_market/api/serialize.rb, line 241
def to_hash(item, role = :none)
  # Check there is a type
  raise "Attempting to serialize class with no type" unless item.instance_variable_defined? "@type"
  hash = Hash[item.get_accessors(role).map do |accessor| 
    value = item.instance_variable_get("@#{accessor.to_s}")
    value = value.to_s unless value.is_a?(String) or value.is_a?(Fixnum) or value.is_a?(Float) or value.is_a?(Hash) or value.is_a?(Array) or value.is_a?(TrueClass) or value.is_a?(FalseClass) 
    [accessor, value] 
    end ]
end
to_json(item, role = :none) click to toggle source

Serialize a class to JSON and include it's type for de-serializing later

  • item - Item to serialize

Returns

JSON

# File lib/onapp_market/api/serialize.rb, line 255
def to_json(item, role = :none)
  # Generate a JSON from the instance variables
  JSON.generate(OnappMarket::API::Serialize.to_hash(item, role))
end