Class: RDF::N3::Writer

Inherits:
Writer show all
Includes:
Util::Logger
Defined in:
vendor/bundler/ruby/2.5.0/bundler/gems/rdf-n3-f6621862bdfe/lib/rdf/n3/writer.rb

Overview

A Turtle serialiser in Ruby

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(:n3)         #=> RDF::N3::Writer
RDF::Writer.for("etc/test.n3")
RDF::Writer.for("etc/test.ttl")
RDF::Writer.for(file_name:      "etc/test.n3")
RDF::Writer.for(file_name:      "etc/test.ttl")
RDF::Writer.for(file_extension: "n3")
RDF::Writer.for(file_extension: "ttl")
RDF::Writer.for(content_type:   "text/n3")

Serializing RDF graph into an Turtle file

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

Serializing RDF statements into an Turtle file

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

Serializing RDF statements into an Turtle string

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

Creating @base and @prefix definitions in output

RDF::N3::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:

Constant Summary collapse

QNAME =
Meta::REGEXPS[:"http://www.w3.org/2000/10/swap/grammar/n3#qname"]

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 inherited from Writer

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_prologue, #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?

Constructor Details

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

Initializes the Turtle writer instance.

Parameters:

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

    the output stream

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

    any additional options

Options Hash (options):

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

    the encoding to use on the output stream (Ruby 1.9+)

  • :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.

  • :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).

Yields:

  • (writer)

    self

  • (writer)

Yield Parameters:

Yield Returns:

  • (void)


108
109
110
111
112
113
114
115
116
117
118
119
120
# File 'vendor/bundler/ruby/2.5.0/bundler/gems/rdf-n3-f6621862bdfe/lib/rdf/n3/writer.rb', line 108

def initialize(output = $stdout, options = {}, &block)
  super do
    @graph = RDF::Graph.new
    @uri_to_qname = {}
    @uri_to_prefix = {}
    if block_given?
      case block.arity
        when 0 then instance_eval(&block)
        else block.call(self)
      end
    end
  end
end

Instance Attribute Details

#base_uriURI

Returns Base URI used for relativizing URIs

Returns:

  • (URI)

    Base URI used for relativizing URIs



60
61
62
# File 'vendor/bundler/ruby/2.5.0/bundler/gems/rdf-n3-f6621862bdfe/lib/rdf/n3/writer.rb', line 60

def base_uri
  @base_uri
end

#graphGraph

Returns Graph of statements serialized

Returns:

  • (Graph)

    Graph of statements serialized



58
59
60
# File 'vendor/bundler/ruby/2.5.0/bundler/gems/rdf-n3-f6621862bdfe/lib/rdf/n3/writer.rb', line 58

def graph
  @graph
end

Class Method Details

.optionsObject

N3 Writer options



65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'vendor/bundler/ruby/2.5.0/bundler/gems/rdf-n3-f6621862bdfe/lib/rdf/n3/writer.rb', line 65

def self.options
  super + [
    RDF::CLI::Option.new(
      symbol: :max_depth,
      datatype: Integer,
      on: ["--max-depth"],
      description: "Maximum depth for recursively defining resources, defaults to 3.") {|arg| arg.to_i},
    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)},
  ]
end

Instance Method Details

#format_literal(literal, options = {}) ⇒ String

Returns the N-Triples representation of a literal.

Parameters:

Returns:



231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
# File 'vendor/bundler/ruby/2.5.0/bundler/gems/rdf-n3-f6621862bdfe/lib/rdf/n3/writer.rb', line 231

def format_literal(literal, options = {})
  literal = literal.dup.canonicalize! if @options[:canonicalize]
  case literal
  when RDF::Literal
    case literal.datatype
    when RDF::XSD.boolean, RDF::XSD.integer, RDF::XSD.decimal
      literal.to_s
    when RDF::XSD.double
      literal.to_s.sub('E', 'e')  # Favor lower case exponent
    else
      text = quoted(literal.value)
      text << "@#{literal.language}" if literal.has_language?
      text << "^^#{format_uri(literal.datatype)}" if literal.has_datatype?
      text
    end
  else
    quoted(literal.to_s)
  end
end

#format_node(node, options = {}) ⇒ String

Returns the Turtle/N3 representation of a blank node.

Parameters:

Returns:



269
270
271
# File 'vendor/bundler/ruby/2.5.0/bundler/gems/rdf-n3-f6621862bdfe/lib/rdf/n3/writer.rb', line 269

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

#format_uri(uri, options = {}) ⇒ String

Returns the Turtle/N3 representation of a URI reference.

Parameters:

Returns:



257
258
259
260
261
# File 'vendor/bundler/ruby/2.5.0/bundler/gems/rdf-n3-f6621862bdfe/lib/rdf/n3/writer.rb', line 257

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

#get_qname(resource) ⇒ String?

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

Parameters:

Returns:

  • (String, nil)

    value to use to identify URI



162
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
189
190
191
192
193
194
195
196
197
198
199
200
201
# File 'vendor/bundler/ruby/2.5.0/bundler/gems/rdf-n3-f6621862bdfe/lib/rdf/n3/writer.rb', line 162

def get_qname(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

  log_debug {"get_qname(#{resource}), std?}"}
  qname = case
  when @uri_to_qname.has_key?(uri)
    return @uri_to_qname[uri]
  when u = @uri_to_prefix.keys.detect {|u| uri.index(u.to_s) == 0}
    # Use a defined prefix
    prefix = @uri_to_prefix[u]
    prefix(prefix, u) unless u.to_s.empty? # Define for output
    log_debug {"get_qname: add prefix #{prefix.inspect} => #{u}"}
    uri.sub(u.to_s, "#{prefix}:")
  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_qname: add standard prefix #{prefix.inspect} => #{vocab.to_uri}"}
    uri.sub(vocab.to_uri.to_s, "#{prefix}:")
  else
    nil
  end
  
  # Make sure qname is a valid qname
  if qname
    md = QNAME.match(qname)
    qname = nil unless md.to_s.length == qname.length
  end

  @uri_to_qname[uri] = qname
rescue Addressable::URI::InvalidURIError => e
  raise RDF::WriterError, "Invalid URI #{resource.inspect}: #{e.message}"
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



380
381
382
# File 'vendor/bundler/ruby/2.5.0/bundler/gems/rdf-n3-f6621862bdfe/lib/rdf/n3/writer.rb', line 380

def indent(modifier = 0)
  " " * (@depth + modifier)
end

#order_subjectsArray<Resource> (protected)

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

Uses #top_classes and #base_uri.

Returns:



307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
# File 'vendor/bundler/ruby/2.5.0/bundler/gems/rdf-n3-f6621862bdfe/lib/rdf/n3/writer.rb', line 307

def order_subjects
  seen = {}
  subjects = []
  
  # Start with base_uri
  if base_uri && @subjects.keys.include?(base_uri)
    subjects << base_uri
    seen[base_uri] = true
  end
  log_debug {"subjects1: #{subjects.inspect}"}
  
  # 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.inspect}"}
      subjects << subject
      seen[subject] = true
    end
  end
  log_debug {"subjects2: #{subjects.inspect}"}
  
  # Sort subjects by resources over bnodes, ref_counts and the subject URI itself
  recursable = @subjects.keys.
    select {|s| !seen.include?(s)}.
    map {|r| [r.node? ? 1 : 0, ref_count(r), r]}.
    sort
  
  log_debug {"subjects3: #{subjects.inspect}"}
  subjects += recursable.map{|r| r.last}
  log_debug {"subjects4: #{subjects.inspect}"}
  subjects
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:



301
# File 'vendor/bundler/ruby/2.5.0/bundler/gems/rdf-n3-f6621862bdfe/lib/rdf/n3/writer.rb', line 301

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

#preprocessObject (protected)

Perform any preprocessing of statements required



341
342
343
344
345
346
347
348
349
350
351
# File 'vendor/bundler/ruby/2.5.0/bundler/gems/rdf-n3-f6621862bdfe/lib/rdf/n3/writer.rb', line 341

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

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

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

#preprocess_statement(statement) ⇒ Object (protected)

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

Parameters:



356
357
358
359
360
361
362
363
364
365
366
367
368
369
# File 'vendor/bundler/ruby/2.5.0/bundler/gems/rdf-n3-f6621862bdfe/lib/rdf/n3/writer.rb', line 356

def preprocess_statement(statement)
  #log_debug {"preprocess: #{statement.inspect}"}
  references = ref_count(statement.object) + 1
  @references[statement.object] = references
  @subjects[statement.subject] = true
  
  # Pre-fetch qnames, to fill prefixes
  get_qname(statement.subject)
  get_qname(statement.predicate)
  get_qname(statement.object)
  get_qname(statement.object.datatype) if statement.object.literal? && statement.object.datatype

  @references[statement.predicate] = ref_count(statement.predicate) + 1
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:



401
402
403
404
405
406
407
408
# File 'vendor/bundler/ruby/2.5.0/bundler/gems/rdf-n3-f6621862bdfe/lib/rdf/n3/writer.rb', line 401

def quoted(string)
  if string.to_s.match(/[\t\n\r]/)
    string = string.gsub('\\', '\\\\\\\\').gsub('"""', '\\"""')
    %("""#{string}""")
  else
    "\"#{escaped(string)}\""
  end
end

#ref_count(node) ⇒ Integer (protected)

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

Returns:



373
374
375
# File 'vendor/bundler/ruby/2.5.0/bundler/gems/rdf-n3-f6621862bdfe/lib/rdf/n3/writer.rb', line 373

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

#relativize(uri) ⇒ String (protected)

If base_uri is defined, use it to try to make uri relative

Parameters:

  • uri (#to_s)

Returns:



289
290
291
292
# File 'vendor/bundler/ruby/2.5.0/bundler/gems/rdf-n3-f6621862bdfe/lib/rdf/n3/writer.rb', line 289

def relativize(uri)
  uri = uri.to_s
  base_uri ? uri.sub(base_uri.to_s, "") : uri
end

#resetObject (protected)

Reset internal helper instance variables



385
386
387
388
389
390
391
392
393
394
# File 'vendor/bundler/ruby/2.5.0/bundler/gems/rdf-n3-f6621862bdfe/lib/rdf/n3/writer.rb', line 385

def reset
  @depth = 0
  @lists = {}
  @namespaces = {}
  @references = {}
  @serialized = {}
  @subjects = {}
  @shortNames = {}
  @started = false
end

#sort_properties(properties) ⇒ Array<String>

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

Parameters:

Returns:

  • (Array<String>)

    ] Ordered list of properties. Uses predicate_order.



207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
# File 'vendor/bundler/ruby/2.5.0/bundler/gems/rdf-n3-f6621862bdfe/lib/rdf/n3/writer.rb', line 207

def sort_properties(properties)
  # Make sorted list of properties
  prop_list = []
  
  predicate_order.each do |prop|
    next unless properties[prop.to_s]
    prop_list << prop.to_s
  end
  
  properties.keys.sort.each do |prop|
    next if prop_list.include?(prop.to_s)
    prop_list << prop.to_s
  end
  
  log_debug {"sort_properties: #{prop_list.join(', ')}"}
  prop_list
end

#start_documentObject (protected)

Output @base and @prefix definitions



275
276
277
278
279
280
281
282
283
284
# File 'vendor/bundler/ruby/2.5.0/bundler/gems/rdf-n3-f6621862bdfe/lib/rdf/n3/writer.rb', line 275

def start_document
  @started = true
  
  @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

#top_classesArray<URI> (protected)

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

Returns:



296
# File 'vendor/bundler/ruby/2.5.0/bundler/gems/rdf-n3-f6621862bdfe/lib/rdf/n3/writer.rb', line 296

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

#write_epilogue

This method returns an undefined value.

Outputs the N3 representation of all stored triples.

See Also:



139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
# File 'vendor/bundler/ruby/2.5.0/bundler/gems/rdf-n3-f6621862bdfe/lib/rdf/n3/writer.rb', line 139

def write_epilogue
  @max_depth = @options[:max_depth] || 3
  @base_uri = RDF::URI(@options[:base_uri])

  self.reset

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

  preprocess
  start_document

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

  super
end

#write_triple(subject, predicate, object)

This method is abstract.

This method returns an undefined value.

Addes a triple to be serialized

Parameters:

Raises:

  • (NotImplementedError)

    unless implemented in subclass



130
131
132
# File 'vendor/bundler/ruby/2.5.0/bundler/gems/rdf-n3-f6621862bdfe/lib/rdf/n3/writer.rb', line 130

def write_triple(subject, predicate, object)
  @graph.insert(RDF::Statement(subject, predicate, object))
end