Method: JSON::LD::API.compact

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

.compact(input, context, callback = nil, options = {}) {|jsonld| ... } ⇒ Hash

Compacts the given input according to the steps in the Compaction Algorithm. The input must be copied, compacted and returned if there are no errors. If the compaction fails, an appropirate exception must be thrown.

If no context is provided, the input document is compacted using the top-level context of the document

The resulting Hash is returned via the provided callback.

Note that for Ruby, if the callback is not provided and a block is given, it will be yielded

Parameters:

  • input (String, #read, Hash, Array)

    The JSON-LD object to copy and perform the compaction upon.

  • context (String, #read, Hash, Array, JSON::LD::EvaluationContext)

    The base context to use when compacting the input.

  • callback (Proc) (defaults to: nil)

    (&block) Alternative to using block, with same parameters.

  • options (Hash{Symbol => Object}) (defaults to: {})

    See options in #initialize Other options passed to expand

Yields:

  • jsonld

Yield Parameters:

  • jsonld (Hash)

    The compacted JSON-LD document

Returns:

  • (Hash)

    The compacted JSON-LD document

Raises:

See Also:



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

def self.compact(input, context, callback = nil, options = {})
  expanded = result = nil

  # 1) Perform the Expansion Algorithm on the JSON-LD input.
  #    This removes any existing context to allow the given context to be cleanly applied.
  expanded = API.expand(input, nil, nil, options.merge(:debug => nil))

  API.new(expanded, context, options) do
    debug(".compact") {"expanded input: #{expanded.to_json(JSON_STATE)}"}
    result = compact(value, nil)

    # xxx) Add the given context to the output
    result = case result
    when Hash then self.context.serialize.merge(result)
    when Array
      kwgraph = self.context.compact_iri('@graph', :quiet => true)
      self.context.serialize.merge(kwgraph => result)
    when String
      kwid = self.context.compact_iri('@id', :quiet => true)
      self.context.serialize.merge(kwid => result)
    end
  end
  callback.call(result) if callback
  yield result if block_given?
  result
end