lib/openactive/base_model.rb in openactive-0.1.0.rc1 vs lib/openactive/base_model.rb in openactive-0.1.0

- old
+ new

@@ -33,11 +33,11 @@ attr_name = attr_name[1..] if attr_name.start_with?('@') val = value - val = deserialize_value(value) if value.is_a?(Array) || value.is_a?(Hash) + val = deserialize(value) if value.is_a?(Array) || value.is_a?(Hash) return if ["context", "type"].include?(attr_name) # Calling the setter will type-enforce it send("#{attr_name}=", val) @@ -47,14 +47,11 @@ # Returns an object from a given JSON-LD representation. # # @param data [string,Array] If a string is provided, we attempt JSON-decoding first # @return [object] # - def self.deserialize(data) - # If a string is provided, we attempt JSON-decoding first - data = JSON.parse(data) if data.is_a?(String) - + def self.deserialize_class(data) inst = new # If data provided is not an array, return an empty class return inst unless data.is_a?(Array) || data.is_a?(Hash) @@ -63,19 +60,15 @@ end inst end - def deserialize(*data) - self.class.deserialize(data) - end - # Returns a value from a given JSON-LD deserialized array. # # @param value [mixed] If an array is provided, we recursively deserialize it # @return [mixed] - def deserialize_value(value) + def self.deserialize(value) if value.is_a?(Hash) # If an associative array with a type, return its deserialization form, # so that it gets converted from array to object # (associative arrays are still arrays in PHP) if value.key?("@type") || value.key?("type") @@ -85,22 +78,26 @@ # only schema is in a subdir, everything else is flat type = type.split(":")[1] if type.include?(':') && !type.start_with?("schema:") klass = ::OpenActive::Models.const_get(type) - inst = klass.deserialize(value) + inst = klass.deserialize_class(value) return inst end elsif value.is_a?(Array) # NOTE: OpenActive is more strict than schema.org in this regard, so no single element array handling here. # If providing a non-associative array # Loop through it and serialize each item if needed value = value.map do |item| - deserialize_value(item) + deserialize(item) end end value + end + + def deserialize(*data) + self.class.deserialize(*data) end # Returns the JSON-LD representation of the given instance. # # @param obj [::OpenActive::BaseModel] The given instance to convert to JSON-LD