Class: RDF::Format::NTriples

Inherits:
Object
  • Object
show all
Defined in:
lib/rdf/format/ntriples.rb

Overview

Import/Exports a graph to NTriples format.

Defined Under Namespace

Classes: SyntaxError

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(file, graph = nil) ⇒ NTriples

Creates an instance of NTriples for importing an NTriples file into graph.



49
50
51
52
53
54
55
# File 'lib/rdf/format/ntriples.rb', line 49

def initialize(file, graph = nil)
  @lineno = 1
  @charno = 1
  @file = file.respond_to?(:getc) ? file : StringIO.new(file.to_s)
  stretch_buf_to(1)
  @graph = graph.nil? ? RDF::Graph::Memory.new : graph
end

Class Method Details

.export(graph, file) ⇒ Object

Exports a graph to file in NTriples format.



11
12
13
14
15
16
17
18
19
20
# File 'lib/rdf/format/ntriples.rb', line 11

def self.export(graph, file)
  graph.each do |t|
    file.write(export_node(t.subject))
    file.write(' ')
    file.write(export_node(t.predicate))
    file.write(' ')
    file.write(export_node(t.object))
    file.puts('.')
  end
end

.export_node(node) ⇒ Object

Returns a string NTriples representation of node.



23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/rdf/format/ntriples.rb', line 23

def self.export_node(node)
  case
  when RDF::UriNode?(node)
    "<#{node.uri}>"
  when RDF::BlankNode?(node)
    "_:#{node.name}"
  when RDF::PlainLiteralNode?(node)
    "\"#{node.lexical_form}\"" + (node.language_tag.to_s.empty? ? '' : "@#{node.language_tag}")
  when RDF::TypedLiteralNode?(node)
    "\"#{node.lexical_form}\"^^<#{node.datatype_uri}>"
  else
    raise SyntaxError, "Unknown node type"
  end
end

.import(file, graph = nil) ⇒ Object

Imports NTriples input file to graph or creates a new graph if graph is nil.



39
40
41
# File 'lib/rdf/format/ntriples.rb', line 39

def self.import(file, graph = nil)
  NTriples.new(file, graph).import
end

.import_node(str, graph = nil) ⇒ Object

Imports a string NTriples representation of a node into graph or creates a new graph if graph is nil.



44
45
46
# File 'lib/rdf/format/ntriples.rb', line 44

def self.import_node(str, graph = nil)
  NTriples.new(StringIO.new(str), graph).import_node
end

Instance Method Details

#importObject

Runs the import for this NTriples instance, and returns the graph.



58
59
60
61
# File 'lib/rdf/format/ntriples.rb', line 58

def import
  lines unless @file.eof?
  @graph
end

#import_nodeObject

Runs the import for a single node for this NTriples instance, and returns the node.



64
65
66
67
68
69
70
# File 'lib/rdf/format/ntriples.rb', line 64

def import_node
  if ws?
    wses
  end
  
  object
end