class Statham::Serializer
Internal: Serializes/deserializes collection of attributes into/from JSON.
Public Class Methods
Internal: Initializes Serializer
.
attribute_set - AttributeSet
object for definition of the attributes.
Returns new Serializer
object.
# File lib/statham/serializer.rb, line 9 def initialize(attribute_set, implicit_serialization = false) @attribute_set = attribute_set @implicit_serialization = implicit_serialization end
Public Instance Methods
Internal: Serializes object.
object - Object to serialize.
Returns JSON string for the object.
# File lib/statham/serializer.rb, line 19 def dump(object) @implicit_serialization ? serialize_with_attributes(object) : ActiveSupport::JSON.encode(serialize_with_attributes(object)) end
Internal: Deserializes JSON string into object.
json - JSON string to deserialize.
Returns Hash object deserialized from the JSON.
# File lib/statham/serializer.rb, line 30 def load(json) object = if @implicit_serialization ActiveSupport::HashWithIndifferentAccess.new(json || {}) else json ? ActiveSupport::HashWithIndifferentAccess.new(ActiveSupport::JSON.decode(json)) : Hash.new end deserialize_with_attributes(object) end
Protected Instance Methods
Internal: Deserialize values in specified hash object using options used to define attributes.
object - Object to deserialize.
Returns Hash containing deserialized values.
# File lib/statham/serializer.rb, line 64 def deserialize_with_attributes(object) @attribute_set.attributes.inject(object) do |serialized, (name, attribute)| if attribute.default serialized.merge name => attribute.deserialize(object[name], fallback_to_default: !object.has_key?(name)) else object.has_key?(name) ? serialized.merge(name => attribute.deserialize(object[name])) : serialized end end end
Internal: Serialize values in specified hash object using options used to define attributes.
object - Object to serialize.
Returns Hash containing serialized values.
# File lib/statham/serializer.rb, line 48 def serialize_with_attributes(object) @attribute_set.attributes.inject(object) do |serialized, (name, attribute)| if attribute.default || object.has_key?(name) serialized.merge name => attribute.serialize(object[name]) else serialized end end end