lib/mida/item.rb in mida-0.3.0 vs lib/mida/item.rb in mida-0.3.1

- old
+ new

@@ -22,26 +22,32 @@ # Create a new Item object from an +Itemscope+ and validates # its +properties+ # # [itemscope] The itemscope that has been parsed by +Itemscope+ - def initialize(itemscope) + # [validate] Whether to validate the item against known vocabularies + def initialize(itemscope, validate=true) @type = itemscope.type @id = itemscope.id @vocabulary = Mida::Vocabulary.find(@type) @properties = itemscope.properties - validate_properties + validate_properties if validate end # Return a Hash representation # of the form: # { type: 'http://example.com/vocab/review', # id: 'urn:isbn:1-934356-08-5', # properties: {'a name' => 'avalue' } # } def to_h - {type: @type, id: @id, properties: properties_to_h(@properties)} + # Only fill hash with non-nil values + hash = {} + @type and hash[:type] = @type + @id and hash[:id] = @id + @properties.any? and hash[:properties] = properties_to_h(@properties) + hash end def to_s to_h.to_s end @@ -56,11 +62,15 @@ # Validate the properties so that they are in their proper form def validate_properties @properties = @properties.each_with_object({}) do |(property, values), hash| valid_values = validate_values(property, values) - hash[property] = valid_values unless valid_values.nil? + if valid_values.respond_to?(:any?) + hash[property] = valid_values if valid_values.any? + else + hash[property] = valid_values + end end end # Return whether the number of values conforms to +num+ def valid_num_values?(num, values) @@ -75,12 +85,12 @@ end # Return valid values, converted to the correct +DataType+ # or +Item+ and number if necessary def validate_values(property, values) - return nil unless valid_property?(property, values) + return [] unless valid_property?(property, values) prop_num = property_number(property) - return nil unless valid_num_values?(prop_num, values) + return [] unless valid_num_values?(prop_num, values) prop_types = property_types(property) valid_values = values.each_with_object([]) do |value, valid_values| new_value = validate_value(prop_types, value) valid_values << new_value unless new_value.nil?