Class: RDF::Turtle::Writer

Inherits:
Writer
  • Object
show all
Includes:
StreamingWriter
Defined in:
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

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from StreamingWriter

#stream_epilogue, #stream_prologue, #stream_statement

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

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

  • :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 fo numbers and boolean values

Yields:

  • (writer)

    ‘self`

  • (writer)

Yield Parameters:

  • writer (RDF::Writer)
  • writer (RDF::Writer)

Yield Returns:

  • (void)


97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
# File 'lib/rdf/turtle/writer.rb', line 97

def initialize(output = $stdout, options = {}, &block)
  reset
  @graph = RDF::Graph.new
  @uri_to_pname = {}
  @uri_to_prefix = {}
  options = {literal_shorthand: true}.merge(options)
  super do
    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



63
64
65
# File 'lib/rdf/turtle/writer.rb', line 63

def graph
  @graph
end

Instance Method Details

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

Returns the N-Triples representation of a literal.

Parameters:

  • literal (RDF::Literal, String, #to_s)
  • options (Hash{Symbol => Object}) (defaults to: {})

Returns:

  • (String)


246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
# File 'lib/rdf/turtle/writer.rb', line 246

def format_literal(literal, options = {})
  literal = literal.dup.canonicalize! if @options[:canonicalize]
  case literal
  when RDF::Literal
    case @options[:literal_shorthand] && literal.valid? ? literal.datatype : false
    when RDF::XSD.boolean, RDF::XSD.integer, RDF::XSD.decimal
      literal.canonicalize.to_s
    when RDF::XSD.double
      literal.canonicalize.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 representation of a blank node.

Parameters:

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

Returns:

  • (String)


284
285
286
# File 'lib/rdf/turtle/writer.rb', line 284

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

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

Returns the Turtle representation of a URI reference.

Parameters:

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

Returns:

  • (String)


272
273
274
275
276
# File 'lib/rdf/turtle/writer.rb', line 272

def format_uri(uri, options = {})
  md = uri.relativize(base_uri)
  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 QName for the URI, or nil. Adds namespace of QName to defined prefixes

Parameters:

  • resource (RDF::Resource)

Returns:

  • (String, nil)

    value to use to identify URI



178
179
180
181
182
183
184
185
186
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
216
# File 'lib/rdf/turtle/writer.rb', line 178

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.has_key?(uri)
    return @uri_to_pname[uri]
  when u = @uri_to_prefix.keys.sort_by {|u| u.length}.reverse.detect {|u| uri.index(u.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?
      debug("get_pname") {"add prefix #{prefix.inspect} => #{u}"}
      uri.sub(u.to_s, "#{prefix}:")
    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
    debug("get_pname") {"add standard prefix #{prefix.inspect} => #{vocab.to_uri}"}
    uri.sub(vocab.to_uri.to_s, "#{prefix}:")
  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

#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:

  • properties (Hash{String => Array<Resource>})

    A hash of Property to Resource mappings

Returns:

  • (Array<String>)

    ] Ordered list of properties. Uses predicate_order.



222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
# File 'lib/rdf/turtle/writer.rb', line 222

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
  
  debug("sort_properties") {prop_list.join(', ')}
  prop_list
end

#write_epiloguevoid

This method returns an undefined value.

Outputs the Turtle representation of all stored triples.

See Also:



153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
# File 'lib/rdf/turtle/writer.rb', line 153

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

    self.reset

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

    preprocess
    start_document

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

#write_prologuevoid

This method returns an undefined value.

Write out declarations



140
141
142
143
144
145
146
# File 'lib/rdf/turtle/writer.rb', line 140

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

#write_statement(statement) ⇒ void

This method returns an undefined value.

Adds a statement to be serialized

Parameters:

  • statement (RDF::Statement)


117
118
119
120
121
122
123
124
125
# File 'lib/rdf/turtle/writer.rb', line 117

def write_statement(statement)
  case
  when @options[:stream]
    stream_statement(statement)
  else
    # Add to local graph and output in epilogue
    @graph.insert(statement)
  end
end

#write_triple(subject, predicate, object) ⇒ void

This method returns an undefined value.

Adds a triple to be serialized

Parameters:

  • subject (RDF::Resource)
  • predicate (RDF::URI)
  • object (RDF::Value)


133
134
135
# File 'lib/rdf/turtle/writer.rb', line 133

def write_triple(subject, predicate, object)
  write_statement(Statement.new(subject, predicate, object))
end