Class: RDF::Turtle::Writer

Inherits:
Writer show all
Includes:
StreamingWriter, Util::Logger
Defined in:
vendor/bundler/ruby/3.4.0/bundler/gems/rdf-turtle-5818bab04efb/lib/rdf/turtle/writer.rb

Overview

A Turtle serialiser

Note that the natural interface is to write a whole graph at a time. Writing statements or Triples will create a graph to add them to and then serialize the graph.

The writer will add prefix definitions, and use them for creating @prefix definitions, and minting QNames

Examples:

Obtaining a Turtle writer class

RDF::Writer.for(:ttl)         #=> RDF::Turtle::Writer
RDF::Writer.for("etc/test.ttl")
RDF::Writer.for(file_name:       "etc/test.ttl")
RDF::Writer.for(file_extension:  "ttl")
RDF::Writer.for(content_type:    "text/turtle")

Serializing RDF graph into an Turtle file

RDF::Turtle::Writer.open("etc/test.ttl") do |writer|
  writer << graph
end

Serializing RDF statements into an Turtle file

RDF::Turtle::Writer.open("etc/test.ttl") do |writer|
  graph.each_statement do |statement|
    writer << statement
  end
end

Serializing RDF statements into an Turtle string

RDF::Turtle::Writer.buffer do |writer|
  graph.each_statement do |statement|
    writer << statement
  end
end

Serializing RDF statements to a string in streaming mode

RDF::Turtle::Writer.buffer(stream:  true) do |writer|
  graph.each_statement do |statement|
    writer << statement
  end
end

Creating @base and @prefix definitions in output

RDF::Turtle::Writer.buffer(base_uri:  "http://example.com/", prefixes:  {
    nil => "http://example.com/ns#",
    foaf:  "http://xmlns.com/foaf/0.1/"}
) do |writer|
  graph.each_statement do |statement|
    writer << statement
  end
end

Author:

Direct Known Subclasses

RDF::TriG::Writer

Constant Summary

Constants included from Util::Logger

Util::Logger::IOWrapper

Instance Attribute Summary collapse

Attributes inherited from Writer

#options

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Util::Logger

#log_debug, #log_depth, #log_error, #log_fatal, #log_info, #log_recover, #log_recovering?, #log_statistics, #log_warn, #logger

Methods included from StreamingWriter

#stream_epilogue, #stream_prologue, #stream_statement

Methods inherited from Writer

accept?, #base_uri, buffer, #canonicalize?, dump, each, #encoding, #escaped, #flush, for, format, #format_list, #format_term, #node_id, open, #prefix, #prefixes, #prefixes=, #puts, #to_sym, to_sym, #uri_for, #validate?, #write_comment, #write_statement, #write_triples

Methods included from Util::Aliasing::LateBound

#alias_method

Methods included from Writable

#<<, #insert, #insert_graph, #insert_reader, #insert_statement, #insert_statements, #writable?

Methods included from Util::Coercions

#coerce_statements

Constructor Details

#initialize(output = $stdout, **options) {|writer| ... } ⇒ Writer

TODO:

Get version parameter from ACCEPT header parameter

Initializes the Turtle writer instance.

Parameters:

  • output (IO, File) (defaults to: $stdout)

    the output stream

  • options (Hash{Symbol => Object})

    any additional options

Options Hash (**options):

  • :encoding (Encoding) — default: Encoding::UTF_8

    the encoding to use on the output stream

  • :canonicalize (Boolean) — default: false

    whether to canonicalize literals when serializing

  • :prefixes (Hash) — default: Hash.new

    the prefix mappings to use (not supported by all writers)

  • :base_uri (#to_s) — default: nil

    the base URI to use when constructing relative URIs

  • :max_depth (Integer) — default: 3

    Maximum depth for recursively defining resources, defaults to 3

  • :standard_prefixes (Boolean) — default: false

    Add standard prefixes to @prefixes, if necessary.

  • :stream (Boolean) — default: false

    Do not attempt to optimize graph presentation, suitable for streaming large graphs.

  • :default_namespace (String) — default: nil

    URI to use as default namespace, same as prefixes[nil]

  • :unique_bnodes (Boolean) — default: false

    Use unique node identifiers, defaults to using the identifier which the node was originall initialized with (if any).

  • :literal_shorthand (Boolean) — default: true

    Attempt to use Literal shorthands for numbers and boolean values

  • :version (String) — default: "1.2"

    Emit a specific version of RDF ("1.1', "1.2", or "1.2-basic"")

Yields:

  • (writer)

    self

  • (writer)

Yield Parameters:

Yield Returns:

  • (void)


138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
# File 'vendor/bundler/ruby/3.4.0/bundler/gems/rdf-turtle-5818bab04efb/lib/rdf/turtle/writer.rb', line 138

def initialize(output = $stdout, **options, &block)
  @graph = RDF::Graph.new
  @uri_to_pname = {}
  @uri_to_prefix = {}
  @version = options[:version]
  options = {literal_shorthand: true}.merge(options)
  super do
    reset
    if block_given?
      case block.arity
        when 0 then instance_eval(&block)
        else block.call(self)
      end
    end
  end
end

Instance Attribute Details

#graphGraph

Returns Graph of statements serialized.

Returns:

  • (Graph)

    Graph of statements serialized



64
65
66
# File 'vendor/bundler/ruby/3.4.0/bundler/gems/rdf-turtle-5818bab04efb/lib/rdf/turtle/writer.rb', line 64

def graph
  @graph
end

#versionString

Returns RDF Version of output.

Returns:

  • (String)

    RDF Version of output



67
68
69
# File 'vendor/bundler/ruby/3.4.0/bundler/gems/rdf-turtle-5818bab04efb/lib/rdf/turtle/writer.rb', line 67

def version
  @version
end

Class Method Details

.optionsObject

Writer options



72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
# File 'vendor/bundler/ruby/3.4.0/bundler/gems/rdf-turtle-5818bab04efb/lib/rdf/turtle/writer.rb', line 72

def self.options
  super + [
    RDF::CLI::Option.new(
      symbol: :max_depth,
      datatype: Integer,
      on: ["--max-depth DEPTH"],
      description: "Maximum depth for recursively defining resources, defaults to 3.") {true},
    RDF::CLI::Option.new(
      symbol: :stream,
      datatype: TrueClass,
      on: ["--stream"],
      description: "Do not attempt to optimize graph presentation, suitable for streaming large graphs.") {true},
    RDF::CLI::Option.new(
      symbol: :default_namespace,
      datatype: RDF::URI,
      on: ["--default-namespace URI", :REQUIRED],
      description: "URI to use as default namespace, same as prefixes.") {|arg| RDF::URI(arg)},
    RDF::CLI::Option.new(
      symbol: :literal_shorthand,
      datatype: FalseClass,
      on: ["--no-literal-shorthand"],
      description: "Do not attempt to use Literal shorthands fo numbers and boolean values.") {false},
    RDF::CLI::Option.new(
      symbol: :version,
      control: :select,
      datatype: %w{1.1 1.2 1.2-basic},
      on: ["--version"],
      description: "RDF Version."),
  ]
end

Instance Method Details

#blankNodePropertyList(resource, position) ⇒ Object (protected)

Represent resource as a blankNodePropertyList



603
604
605
606
607
608
609
610
611
612
# File 'vendor/bundler/ruby/3.4.0/bundler/gems/rdf-turtle-5818bab04efb/lib/rdf/turtle/writer.rb', line 603

def blankNodePropertyList(resource, position)
  return false unless blankNodePropertyList?(resource, position)

  log_debug("blankNodePropertyList") {resource.to_ntriples}
  subject_done(resource)
  @output.write(position == :subject ? "\n#{indent} [" : '[')
  num_props = log_depth {predicateObjectList(resource, true)}
  @output.write((num_props > 1 ? "\n#{indent(2)}" : "") + (position == :object ? ']' : '] .'))
  true
end

#blankNodePropertyList?(resource, position) ⇒ Boolean (protected)

Can subject be represented as a blankNodePropertyList?

Returns:

  • (Boolean)


593
594
595
596
597
598
599
600
# File 'vendor/bundler/ruby/3.4.0/bundler/gems/rdf-turtle-5818bab04efb/lib/rdf/turtle/writer.rb', line 593

def blankNodePropertyList?(resource, position)
  !resource.statement? && resource.node? &&
    !collection?(resource) &&
    !reifiedTriple?(resource, position) &&
    !in_triple_term?(resource) &&
    (!is_done?(resource) || position == :subject) &&
    ref_count(resource) == (position == :object ? 1 : 0)
end

#bump_reference(resource) ⇒ Integer (protected)

Increase the reference count of this resource

Parameters:

Returns:

  • (Integer)

    resulting reference count



543
544
545
# File 'vendor/bundler/ruby/3.4.0/bundler/gems/rdf-turtle-5818bab04efb/lib/rdf/turtle/writer.rb', line 543

def bump_reference(resource)
  @references[resource] = ref_count(resource) + 1
end

#collection(node, position) ⇒ Object (protected)



567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
# File 'vendor/bundler/ruby/3.4.0/bundler/gems/rdf-turtle-5818bab04efb/lib/rdf/turtle/writer.rb', line 567

def collection(node, position)
  return false if !collection?(node)
  return false if position == :subject && ref_count(node) > 0
  return false if position == :object && prop_count(node) > 0
  #log_debug("collection") {"#{node.to_ntriples}, #{position}"}

  @output.write("(")
  log_depth do
    list = @lists[node]
    log_debug("collection") {list.inspect}
    subject_done(RDF.nil)
    index = 0
    list.each_statement do |st|
      next unless st.predicate == RDF.first
      log_debug {" list this: #{st.subject} first: #{st.object}[#{position}]"}
      @output.write(" ") if index > 0
      path(st.object, position)
      subject_done(st.subject)
      position = :object
      index += 1
    end
  end
  @output.write(')')
end

#collection?(l) ⇒ Boolean (protected)

Checks if l is a valid RDF list, i.e. no nodes have other properties.

Returns:

  • (Boolean)


562
563
564
565
# File 'vendor/bundler/ruby/3.4.0/bundler/gems/rdf-turtle-5818bab04efb/lib/rdf/turtle/writer.rb', line 562

def collection?(l)
  #log_debug("collection?") {l.inspect}
  return @lists.key?(l)
end

#format_literal(literal, **options) ⇒ String

Returns the N-Triples representation of a literal.

Parameters:

Returns:



289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
# File 'vendor/bundler/ruby/3.4.0/bundler/gems/rdf-turtle-5818bab04efb/lib/rdf/turtle/writer.rb', line 289

def format_literal(literal, **options)
  case literal
  when RDF::Literal
    case @options[:literal_shorthand] && literal.valid? ? literal.datatype : false
    when RDF::XSD.boolean
      %w(true false).include?(literal.value) ? literal.value : literal.canonicalize.to_s
    when RDF::XSD.integer
      literal.value.match?(/^[\+\-]?\d+$/) && !canonicalize? ? literal.value : literal.canonicalize.to_s
    when RDF::XSD.decimal
      literal.value.match?(/^[\+\-]?\d+\.\d+?$/) && !canonicalize? ?
        literal.value :
        literal.canonicalize.to_s
    when RDF::XSD.double
      in_form = case literal.value
      when /[\+\-]?\d+\.\d*E[\+\-]?\d+$/i then true
      when /[\+\-]?\.\d+E[\+\-]?\d+$/i    then true
      when /[\+\-]?\d+E[\+\-]?\d+$/i      then true
      else false
      end && !canonicalize?

      in_form ? literal.value : literal.canonicalize.to_s.sub('E', 'e').to_s
    else
      text = quoted(literal.value)
      text << "@#{literal.language}" if literal.language?
      text << "--#{literal.direction}" if literal.direction?
      text << "^^#{format_uri(literal.datatype)}" if literal.datatype?
      text
    end
  else
    quoted(literal.to_s)
  end
end

#format_node(node, **options) ⇒ String

Returns the Turtle representation of a blank node.

Parameters:

Returns:



340
341
342
# File 'vendor/bundler/ruby/3.4.0/bundler/gems/rdf-turtle-5818bab04efb/lib/rdf/turtle/writer.rb', line 340

def format_node(node, **options)
  options[:unique_bnodes] ? node.to_unique_base : node.to_base
end

#format_tripleTerm(statement, **options) ⇒ String

Returns a triple term

Parameters:

Returns:



350
351
352
353
# File 'vendor/bundler/ruby/3.4.0/bundler/gems/rdf-turtle-5818bab04efb/lib/rdf/turtle/writer.rb', line 350

def format_tripleTerm(statement, **options)
  log_debug("tripleTerm") {"#{statement.to_ntriples}"}
  "<<(%s %s %s)>>" % statement.to_a.map { |value| format_term(value, **options) }
end

#format_uri(uri, **options) ⇒ String

Returns the Turtle representation of a URI reference.

Parameters:

Returns:



328
329
330
331
332
# File 'vendor/bundler/ruby/3.4.0/bundler/gems/rdf-turtle-5818bab04efb/lib/rdf/turtle/writer.rb', line 328

def format_uri(uri, **options)
  md = uri.relativize(base_uri)
  log_debug("relativize") {"#{uri.to_ntriples} => #{md.inspect}"} if md != uri.to_s
  md != uri.to_s ? "<#{md}>" : (get_pname(uri) || "<#{uri}>")
end

#get_pname(resource) ⇒ String?

Return a PName for the URI, or nil. Adds namespace of PName to defined prefixes

Parameters:

Returns:

  • (String, nil)

    value to use to identify URI



220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
# File 'vendor/bundler/ruby/3.4.0/bundler/gems/rdf-turtle-5818bab04efb/lib/rdf/turtle/writer.rb', line 220

def get_pname(resource)
  case resource
  when RDF::Node
    return options[:unique_bnodes] ? resource.to_unique_base : resource.to_base
  when RDF::URI
    uri = resource.to_s
  else
    return nil
  end

  pname = case
  when @uri_to_pname.key?(uri)
    return @uri_to_pname[uri]
  when u = @uri_to_prefix.keys.sort_by {|uu| uu.length}.reverse.detect {|uu| uri.index(uu.to_s) == 0}
    # Use a defined prefix
    prefix = @uri_to_prefix[u]
    unless u.to_s.empty?
      prefix(prefix, u) unless u.to_s.empty?
      log_debug("get_pname") {"add prefix #{prefix.inspect} => #{u}"}
      # Escape suffix, as necessary
      RDF::URI(uri).pname(prefixes: {prefix => u})
    end
  when @options[:standard_prefixes] && vocab = RDF::Vocabulary.each.to_a.detect {|v| uri.index(v.to_uri.to_s) == 0}
    prefix = vocab.__name__.to_s.split('::').last.downcase
    @uri_to_prefix[vocab.to_uri.to_s] = prefix
    prefix(prefix, vocab.to_uri) # Define for output
    log_debug("get_pname") {"add standard prefix #{prefix.inspect} => #{vocab.to_uri}"}
    RDF::URI(uri).pname(prefixes: {prefix => vocab.to_uri})
  else
    nil
  end

  # Make sure pname is a valid pname
  if pname
    md = Terminals::PNAME_LN.match(pname) || Terminals::PNAME_NS.match(pname)
    pname = nil unless md.to_s.length == pname.length
  end

  @uri_to_pname[uri] = pname
end

#in_triple_term?(resource) ⇒ Boolean (protected)

Resource is used within a triple term

Returns:

  • (Boolean)


557
558
559
# File 'vendor/bundler/ruby/3.4.0/bundler/gems/rdf-turtle-5818bab04efb/lib/rdf/turtle/writer.rb', line 557

def in_triple_term?(resource)
  @in_triple_term.key?(resource)
end

#indent(modifier = 0) ⇒ String (protected)

Returns indent string multiplied by the depth

Parameters:

  • modifier (Integer) (defaults to: 0)

    Increase depth by specified amount

Returns:

  • (String)

    A number of spaces, depending on current depth



495
496
497
# File 'vendor/bundler/ruby/3.4.0/bundler/gems/rdf-turtle-5818bab04efb/lib/rdf/turtle/writer.rb', line 495

def indent(modifier = 0)
  " " * (@options.fetch(:log_depth, log_depth) * 2 + modifier)
end

#is_done?(subject) ⇒ Boolean (protected)

Returns:

  • (Boolean)


547
548
549
# File 'vendor/bundler/ruby/3.4.0/bundler/gems/rdf-turtle-5818bab04efb/lib/rdf/turtle/writer.rb', line 547

def is_done?(subject)
  @serialized.include?(subject)
end

#objectList(subject, predicate, objects) ⇒ Object (protected)

Render an objectList having a common subject and predicate



685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
# File 'vendor/bundler/ruby/3.4.0/bundler/gems/rdf-turtle-5818bab04efb/lib/rdf/turtle/writer.rb', line 685

def objectList(subject, predicate, objects)
  log_debug("objectList") {objects.inspect}
  return if objects.empty?

  objects.each_with_index do |obj, i|
    if i > 0 && blankNodePropertyList?(obj, :object)
      @output.write ", "
    elsif i > 0
      @output.write ",\n#{indent(4)}"
    end
    path(obj, :object)

    # If there is a reifier for this statement, write that out
    tt = RDF::Statement(subject, predicate, obj)
    reifs = @reification.select {|k, v| v.include?(tt)}.keys
    reifs.each do |reif|
      @as_reifiedTriple[reif] = true
      if reif.iri? || ref_count(reif) > 0
        @output.write ' ~ '
        p_term(reif, :subject)
      end
      @output.write ' {| '
      predicateObjectList(reif, true)
      @output.write ' |}'
      subject_done(reif)
    end
  end
end

#order_subjectsArray<Resource> (protected)

Order subjects for output. Override this to output subjects in another order.

Uses #top_classes and #base_uri.

Returns:



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
# File 'vendor/bundler/ruby/3.4.0/bundler/gems/rdf-turtle-5818bab04efb/lib/rdf/turtle/writer.rb', line 380

def order_subjects
  seen = {}
  subjects = []

  # Start with base_uri
  if base_uri && @subjects.key?(base_uri)
    subjects << RDF::URI(base_uri)
    seen[RDF::URI(base_uri)] = true
  end

  # Add distinguished classes
  top_classes.each do |class_uri|
    graph.query({predicate:  RDF.type, object:  class_uri}).
      map {|st| st.subject}.
      sort.
      uniq.
      each do |subject|
      log_debug("order_subjects") {subject.to_ntriples}
      subjects << subject
      seen[subject] = true
    end
  end

  # Mark as seen lists that are part of another list
  @lists.values.map(&:statements).
    flatten.each do |st|
      seen[st.object] = true if @lists.key?(st.object)
    end

  # List elements which are bnodes should not be targets for top-level serialization
  list_elements = @lists.values.map(&:to_a).flatten.select(&:node?).compact

  # Sort subjects by resources and statements over bnodes, ref_counts and the subject URI itself
  recursable = (@subjects.keys - list_elements).
    select {|s| !seen.include?(s)}.
    map {|r| [r.node? ? 2 : (r.statement? ? 1 : 0), ref_count(r), r]}.
    sort

  # Sort recursable unto those that are not reifiers and those that are, so that reifieres come last.
  subjects + recursable.map{|r| r.last}.partition {|r| !@reification.key?(r)}.flatten
end

#p_term(resource, position) ⇒ Object (protected)

Default singular resource representation.



648
649
650
651
652
653
654
655
656
# File 'vendor/bundler/ruby/3.4.0/bundler/gems/rdf-turtle-5818bab04efb/lib/rdf/turtle/writer.rb', line 648

def p_term(resource, position)
  #log_debug("p_term") {"#{resource.to_ntriples}, #{position}"}
  l = if resource == RDF.nil
    "()"
  else
    format_term(resource, **options)
  end
  @output.write(l)
end

#path(resource, position) ⇒ Object (protected)

Represent a resource in subject, predicate or object position. Use either collection, blankNodePropertyList or singular resource notation.

Raises:



660
661
662
663
664
665
666
667
668
669
670
671
672
673
# File 'vendor/bundler/ruby/3.4.0/bundler/gems/rdf-turtle-5818bab04efb/lib/rdf/turtle/writer.rb', line 660

def path(resource, position)
  log_debug("path") do
    "#{resource.to_ntriples}, " +
    "pos: #{position}, " +
    "()?: #{collection?(resource)}, " +
    "[]?: #{blankNodePropertyList?(resource, position)}, " +
    "rc: #{ref_count(resource)}"
  end
  raise RDF::WriterError, "Cannot serialize resource '#{resource}'" unless
    collection(resource, position) ||
    reifiedTriple(resource, position) ||
    blankNodePropertyList(resource, position) ||
    p_term(resource, position)
end

#predicate(resource) ⇒ Object (protected)



675
676
677
678
679
680
681
682
# File 'vendor/bundler/ruby/3.4.0/bundler/gems/rdf-turtle-5818bab04efb/lib/rdf/turtle/writer.rb', line 675

def predicate(resource)
  log_debug("predicate") {resource.to_ntriples}
  if resource == RDF.type
    @output.write("a")
  else
    path(resource, :predicate)
  end
end

#predicate_orderArray<URI> (protected)

Defines order of predicates to to emit at begninning of a resource description. Defaults to \[rdf:type, rdfs:label, dc:title\]

Returns:



374
# File 'vendor/bundler/ruby/3.4.0/bundler/gems/rdf-turtle-5818bab04efb/lib/rdf/turtle/writer.rb', line 374

def predicate_order; [RDF.type, RDF::RDFS.label, RDF::URI("http://purl.org/dc/terms/title")]; end

#predicateObjectList(subject, from_bpl = false) ⇒ Integer (protected)

Render a predicateObjectList having a common subject.

Returns:

  • (Integer)

    the number of properties serialized



716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
# File 'vendor/bundler/ruby/3.4.0/bundler/gems/rdf-turtle-5818bab04efb/lib/rdf/turtle/writer.rb', line 716

def predicateObjectList(subject, from_bpl = false)
  properties = @subjects.fetch(subject, {})

  prop_list = sort_properties(properties)
  prop_list -= [RDF.first, RDF.rest] if @lists.key?(subject)
  prop_list -= [RDF.reifies] if @as_reifiedTriple.key?(subject)
  log_debug("predicateObjectList") {prop_list.inspect}
  return 0 if prop_list.empty?

  @output.write("\n#{indent(2)}") if properties.keys.length > 1 && from_bpl
  prop_list.each_with_index do |prop, i|
    begin
      @output.write(";\n#{indent(2)}") if i > 0
      predicate(prop)
      @output.write(" ")
      objectList(subject, prop, properties[prop])
    end
  end
  properties.keys.length
end

#preprocessObject (protected)

Perform any preprocessing of statements required



423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
# File 'vendor/bundler/ruby/3.4.0/bundler/gems/rdf-turtle-5818bab04efb/lib/rdf/turtle/writer.rb', line 423

def preprocess
  # Load defined prefixes
  (@options[:prefixes] || {}).each_pair do |k, v|
    @uri_to_prefix[v.to_s] = k
  end

  prefix(nil, @options[:default_namespace]) if @options[:default_namespace]

  case
  when @options[:stream]
  else
    @options[:prefixes] = {}  # Will define actual used when matched

    @graph.each {|statement| preprocess_statement(statement)}
  end
end

#preprocess_statement(statement, as_subject: true) ⇒ Object (protected)

Perform any statement preprocessing required. This is used to perform reference counts and determine required prefixes.

Parameters:

  • statement (Statement)
  • as_subject (Boolean) (defaults to: true)

    Count as a graph subject



444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
# File 'vendor/bundler/ruby/3.4.0/bundler/gems/rdf-turtle-5818bab04efb/lib/rdf/turtle/writer.rb', line 444

def preprocess_statement(statement, as_subject: true)
  #log_debug("preprocess") {statement.to_ntriples}
  bump_reference(statement.object)

  # Set RDF version to 1.2, if unset and required.
  if version.nil? && (statement.object.statement? || statement.object.literal? && statement.object.direction?)
    @version = "1.2"
  end

  # TODO: what to do if version is "1.1" or "1.2-basic"?

  # Also count references of triple terms
  preprocess_statement(statement.object, as_subject: false) if statement.object.statement?

  # Count properties of this subject
  if as_subject
    (@subjects[statement.subject] ||= {})[statement.predicate] ||= []
    @subjects[statement.subject][statement.predicate] << statement.object
  else
    # Terms of statement are in triple terms
    statement.to_a.each {|t| @in_triple_term[t] = true}
  end

  # If it fits, allow this to be rendered as a reifiedTriple
  if statement.object.statement? && statement.predicate == RDF.reifies
    @reification[statement.subject] ||= []
    @reification[statement.subject] << statement.object unless
      @reification[statement.subject].include?(statement.object)
  end

  # Collect lists
  if statement.predicate == RDF.first
    l = RDF::List.new(subject: statement.subject, graph: graph)
    @lists[statement.subject] = l if l.valid?
  end

  if statement.object == RDF.nil || statement.subject == RDF.nil
    # Add an entry for the list tail
    @lists[RDF.nil] ||= RDF::List[]
  end

  # Pre-fetch pnames, to fill prefixes
  get_pname(statement.subject)
  get_pname(statement.predicate)
  get_pname(statement.object)
  get_pname(statement.object.datatype) if statement.object.literal? && statement.object.datatype
end

#prop_count(subject) ⇒ Integer (protected)

Return the number of statements having this resource as a subject other than for list properties

Returns:



528
529
530
531
532
# File 'vendor/bundler/ruby/3.4.0/bundler/gems/rdf-turtle-5818bab04efb/lib/rdf/turtle/writer.rb', line 528

def prop_count(subject)
  @subjects.fetch(subject, {}).
    reject {|p, o| [RDF.type, RDF.first, RDF.rest, RDF.reifies].include?(p)}.
    values.flatten.length
end

#quoted(string) ⇒ String (protected)

Use single- or multi-line quotes. If literal contains \t, \n, or \r, use a multiline quote, otherwise, use a single-line

Parameters:

Returns:



516
517
518
519
520
521
522
523
524
# File 'vendor/bundler/ruby/3.4.0/bundler/gems/rdf-turtle-5818bab04efb/lib/rdf/turtle/writer.rb', line 516

def quoted(string)
  if string.to_s.match(/[\t\n\r]/)
    string = string.gsub('\\', '\\\\\\\\').gsub('"', '\\"')

    %("""#{string}""")
  else
    "\"#{escaped(string)}\""
  end
end

#ref_count(resource) ⇒ Integer (protected)

Return the number of times this node has been referenced in the object position

Returns:



536
537
538
# File 'vendor/bundler/ruby/3.4.0/bundler/gems/rdf-turtle-5818bab04efb/lib/rdf/turtle/writer.rb', line 536

def ref_count(resource)
  @references.fetch(resource, 0)
end

#reifiedTriple(resource, position) ⇒ Object (protected)

Render a reifiedTriple



621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
# File 'vendor/bundler/ruby/3.4.0/bundler/gems/rdf-turtle-5818bab04efb/lib/rdf/turtle/writer.rb', line 621

def reifiedTriple(resource, position)
  return false unless reifiedTriple?(resource, position)
  write_id = resource.iri? || ref_count(resource) > 1
  @as_reifiedTriple[resource] = true  # Prevent rdf:reifies from being emitted

  log_debug("reifiedTriple") {resource.to_ntriples}
  subject_done(resource)
  # There may be multiple reifiedTriples using this resource
  @reification[resource].each do |tt|
    @output.write(position == :subject ? "\n#{indent} << " : '<< ')
    reifiedTriple(tt.subject, :object) || p_term(tt.subject, :object)
    @output.write(' ')
    predicate(tt.predicate)
    @output.write(' ')
    reifiedTriple(tt.object, :object) || p_term(tt.object, :object)

    if write_id
      # Only need to output blank node identifiers if they have more than one reference
      @output.write(' ~')
      p_term(resource, :subject)
    end
    @output.write(' >>')
  end
  true
end

#reifiedTriple?(resource, position) ⇒ Boolean (protected)

Is this a reifiedTriple?

Returns:

  • (Boolean)


615
616
617
618
# File 'vendor/bundler/ruby/3.4.0/bundler/gems/rdf-turtle-5818bab04efb/lib/rdf/turtle/writer.rb', line 615

def reifiedTriple?(resource, position)
  @reification.key?(resource) &&
  (position == :subject ? (prop_count(resource) > 0) : (prop_count(resource) == 0))
end

#resetObject (protected)

Reset internal helper instance variables



500
501
502
503
504
505
506
507
508
509
# File 'vendor/bundler/ruby/3.4.0/bundler/gems/rdf-turtle-5818bab04efb/lib/rdf/turtle/writer.rb', line 500

def reset
  @lists = {}

  @references = {}
  @serialized = {}
  @subjects = {}
  @reification = {}
  @as_reifiedTriple = {}
  @in_triple_term = {}
end

#sort_properties(properties) ⇒ Array<RDF::URI>

Take a hash from predicate uris to lists of values. Sort the lists of values. Return a sorted list of properties.

Parameters:

Returns:

  • (Array<RDF::URI>)

    ] Ordered list of properties. Uses predicate_order.



265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
# File 'vendor/bundler/ruby/3.4.0/bundler/gems/rdf-turtle-5818bab04efb/lib/rdf/turtle/writer.rb', line 265

def sort_properties(properties)
  # Make sorted list of properties
  prop_list = []

  predicate_order.each do |prop|
    next unless properties[prop]
    prop_list << prop
  end

  properties.keys.sort.each do |prop|
    next if prop_list.include?(prop)
    prop_list << prop
  end

  log_debug("sort_properties") {prop_list.join(', ')}
  prop_list
end

#start_documentObject (protected)

Output @base, @prefix, and @version definitions



357
358
359
360
361
362
363
364
365
# File 'vendor/bundler/ruby/3.4.0/bundler/gems/rdf-turtle-5818bab04efb/lib/rdf/turtle/writer.rb', line 357

def start_document
  @output.write("#{indent}@version #{version.inspect} .\n") if version
  @output.write("#{indent}@base <#{base_uri}> .\n") unless base_uri.to_s.empty?

  log_debug("start_document") {prefixes.inspect}
  prefixes.keys.sort_by(&:to_s).each do |prefix|
    @output.write("#{indent}@prefix #{prefix}: <#{prefixes[prefix]}> .\n")
  end
end

#statement(subject) ⇒ Object (protected)



747
748
749
750
751
752
# File 'vendor/bundler/ruby/3.4.0/bundler/gems/rdf-turtle-5818bab04efb/lib/rdf/turtle/writer.rb', line 747

def statement(subject)
  log_debug("statement") {"#{subject.to_ntriples}, bnodePL?: #{blankNodePropertyList?(subject, :subject)}"}
  subject_done(subject)
  blankNodePropertyList(subject, :subject) || triples(subject)
  @output.puts
end

#subject_done(subject) ⇒ Object (protected)

Mark a subject as done.



552
553
554
# File 'vendor/bundler/ruby/3.4.0/bundler/gems/rdf-turtle-5818bab04efb/lib/rdf/turtle/writer.rb', line 552

def subject_done(subject)
  @serialized[subject] = true
end

#top_classesArray<URI> (protected)

Defines rdf:type of subjects to be emitted at the beginning of the graph. Defaults to rdfs:Class

Returns:



369
# File 'vendor/bundler/ruby/3.4.0/bundler/gems/rdf-turtle-5818bab04efb/lib/rdf/turtle/writer.rb', line 369

def top_classes; [RDF::RDFS.Class]; end

#triples(subject) ⇒ Object (protected)

Render triples having the same subject using an explicit subject



738
739
740
741
742
743
744
745
# File 'vendor/bundler/ruby/3.4.0/bundler/gems/rdf-turtle-5818bab04efb/lib/rdf/turtle/writer.rb', line 738

def triples(subject)
  @output.write("\n#{indent}")
  path(subject, :subject)
  @output.write(" ")
  num_props = predicateObjectList(subject)
  @output.write("#{num_props > 0 ? ' ' : ''}.")
  true
end

#write_epilogue

This method returns an undefined value.

Outputs the Turtle representation of all stored triples.

See Also:



187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
# File 'vendor/bundler/ruby/3.4.0/bundler/gems/rdf-turtle-5818bab04efb/lib/rdf/turtle/writer.rb', line 187

def write_epilogue
  case
  when @options[:stream]
    stream_epilogue
  else
    @max_depth = @options[:max_depth] || 3

    self.reset

    log_debug("\nserialize") {"graph: #{@graph.size}"}

    preprocess

    start_document

    # Remove lists that are referenced and have non-list properties;
    # these are legal, but can't be serialized as lists
    @lists.reject! do |node, list|
      ref_count(node) > 0 && prop_count(node) > 0
    end

    order_subjects.each do |subject|
      unless is_done?(subject)
        statement(subject)
      end
    end
  end
  super
end

#write_prologue

This method returns an undefined value.

Write out declarations



173
174
175
176
177
178
179
180
# File 'vendor/bundler/ruby/3.4.0/bundler/gems/rdf-turtle-5818bab04efb/lib/rdf/turtle/writer.rb', line 173

def write_prologue
  case
  when @options[:stream]
    stream_prologue
  else
  end
  super
end

#write_triple(subject, predicate, object)

This method returns an undefined value.

Adds a triple to be serialized

Parameters:



161
162
163
164
165
166
167
168
# File 'vendor/bundler/ruby/3.4.0/bundler/gems/rdf-turtle-5818bab04efb/lib/rdf/turtle/writer.rb', line 161

def write_triple(subject, predicate, object)
  statement = RDF::Statement.new(subject, predicate, object)
  if @options[:stream]
    stream_statement(statement)
  else
    @graph.insert(statement)
  end
end