Method: JSON::LD::Utils#add_value

Defined in:
lib/json/ld/utils.rb

#add_value(subject, property, value, property_is_array: false, value_is_array: false, allow_duplicate: true) ⇒ Object

Adds a value to a subject. If the value is an array, all values in the array will be added.

Parameters:

  • subject (Hash)

    the hash to add the value to.

  • property (String)

    the property that relates the value to the subject.

  • value (Object)

    the value to add.

  • property_is_array (Boolean) (defaults to: false)

    (false) true if the property is always an array, false if not.

  • value_is_array (Boolean) (defaults to: false)

    (false) true if the value to be added should be preserved as an array (lists)

  • allow_duplicate (Boolean) (defaults to: true)

    (true) true to allow duplicates, false not to (uses

    a simple shallow comparison of subject ID or value).
    


163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
# File 'lib/json/ld/utils.rb', line 163

def add_value(subject, property, value, property_is_array: false, value_is_array: false, allow_duplicate: true)
  if value_is_array
    subject[property] = value
  elsif value.is_a?(Array)
    subject[property] = [] if value.empty? && property_is_array
    value.each do |v|
      add_value(subject, property, v,
        property_is_array: property_is_array, allow_duplicate: allow_duplicate)
    end
  elsif subject[property]
    # check if subject already has value if duplicates not allowed
    _has_value = !allow_duplicate && has_value?(subject, property, value)

    # make property an array if value not present or always an array
    if !subject[property].is_a?(Array) && (!_has_value || property_is_array)
      subject[property] =
        [subject[property]]
    end
    subject[property] << value unless _has_value
  else
    subject[property] = property_is_array ? [value] : value
  end
end