Method: JSON::LD::API.toRdf

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

.toRdf(input, options = {}) {|statement| ... } ⇒ Array<RDF::Statement> Also known as: toRDF

Processes the input according to the RDF Conversion Algorithm, calling the provided callback for each triple generated.

Parameters:

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

    The JSON-LD object to process when outputting statements.

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

    See options in #initialize Options passed to expand

Options Hash (options):

  • :produceGeneralizedRdf (Boolean) — default: false

    If true, output will include statements having blank node predicates, otherwise they are dropped.

Yields:

  • statement

Yield Parameters:

  • statement (RDF::Statement)

Returns:

  • (Array<RDF::Statement>)

    if no block given

Raises:



366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
# File 'lib/json/ld/api.rb', line 366

def self.toRdf(input, options = {}, &block)
  results = []
  results.extend(RDF::Enumerable)

  # Expand input to simplify processing
  expanded_input = API.expand(input, options)

  API.new(expanded_input, nil, options) do
    # 1) Perform the Expansion Algorithm on the JSON-LD input.
    #    This removes any existing context to allow the given context to be cleanly applied.
    debug(".toRdf") {"expanded input: #{expanded_input.to_json(JSON_STATE)}"}

    # Generate _nodeMap_
    node_map = Hash.ordered
    node_map['@default'] = Hash.ordered
    generate_node_map(expanded_input, node_map)
    debug(".toRdf") {"node map: #{node_map.to_json(JSON_STATE)}"}

    # Start generating statements
    node_map.each do |graph_name, graph|
      context = as_resource(graph_name) unless graph_name == '@default'
      debug(".toRdf") {"context: #{context ? context.to_ntriples : 'null'}"}
      # Drop results for graphs which are named with relative IRIs
      if graph_name.is_a?(RDF::URI) && !graph_name.absolute
        debug(".toRdf") {"drop relative graph_name: #{statement.to_ntriples}"}
        next
      end
      graph_to_rdf(graph).each do |statement|
        next if statement.predicate.node? && !options[:produceGeneralizedRdf]
        # Drop results with relative IRIs
        relative = statement.to_a.any? do |r|
          case r
          when RDF::URI
            r.relative?
          when RDF::Literal
            r.has_datatype? && r.datatype.relative?
          else
            false
          end
        end
        if relative
          debug(".toRdf") {"drop statement with relative IRIs: #{statement.to_ntriples}"}
          next
        end

        statement.context = context if context
        if block_given?
          yield statement
        else
          results << statement
        end
      end
    end
  end
  results
end