Class: RDF::Vocabulary::Writer

Inherits:
Writer
  • Object
show all
Includes:
Util::Logger
Defined in:
lib/rdf/vocab/writer.rb

Overview

Vocabulary format specification. This can be used to generate a Ruby class definition from a loaded vocabulary.

Definitions can include recursive term definitions, when the value of a property is a blank-node term. They can also include list definitions, to provide a reasonable way to represent ‘owl:unionOf`-type relationships.

Examples:

a simple term definition

property :comment,
  comment: %(A description of the subject resource.),
  domain: "rdfs:Resource",
  label: "comment",
  range: "rdfs:Literal",
  isDefinedBy: %(rdfs:),
  type: "rdf:Property"

an embedded skos:Concept

term :ad,
  exactMatch: [term(
      type: "skos:Concept",
      inScheme: "country:iso3166-1-alpha-2",
      notation: %(ad)
    ), term(
      type: "skos:Concept",
      inScheme: "country:iso3166-1-alpha-3",
      notation: %(and)
    )],
  "foaf:name": "Andorra",
  isDefinedBy: "country:",
  type: "http://sweet.jpl.nasa.gov/2.3/humanJurisdiction.owl#Country"

owl:unionOf

property :duration,
  comment: %(The duration of a track or a signal in ms),
  domain: term(
      "owl:unionOf": list("mo:Track", "mo:Signal"),
      type: "owl:Class"
    ),
  isDefinedBy: "mo:",
  "mo:level": "1",
  range: "xsd:float",
  type: "owl:DatatypeProperty",
  "vs:term_status": "testing"

term definition with language-tagged strings

property :actor,
  comment: {en: "Subproperty of as:attributedTo that identifies the primary actor"},
  domain: "https://www.w3.org/ns/activitystreams#Activity",
  label: {en: "actor"},
  range: term(
      type: "http://www.w3.org/2002/07/owl#Class",
      unionOf: list("https://www.w3.org/ns/activitystreams#Object", "https://www.w3.org/ns/activitystreams#Link")
    ),
  subPropertyOf: "https://www.w3.org/ns/activitystreams#attributedTo",
  type: "http://www.w3.org/2002/07/owl#ObjectProperty"

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

accept?, #base_uri, buffer, #canonicalize?, dump, each, #encoding, #flush, for, format, #format_list, #format_literal, #format_node, #format_quotedTriple, #format_term, #format_tripleTerm, #format_uri, open, #prefix, #prefixes, #prefixes=, to_sym, #to_sym, #validate?, #write_comment, #write_prologue, #write_statement, #write_triples

Methods included from Util::Aliasing::LateBound

#alias_method

Methods included from Writable

#<<, #insert, #writable?

Constructor Details

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

Initializes the writer.

Parameters:

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

    the output stream

  • base_uri (RDF::URI)

    URI of this vocabulary

  • options (Hash{Symbol => Object})

    ({})

    any additional options. See Writer#initialize

Options Hash (**options):

  • :class_name (String)

    Class name for this vocabulary

  • :module_name (String) — default: "RDF"

    Module name for this vocabulary

  • extra (Hash)

    Extra properties to add to the output (programatic only)

  • patch (String)

    An LD Patch to run against the graph before writing

  • strict (Boolean) — default: false

    Create an RDF::StrictVocabulary instead of an RDF::Vocabulary

Yields:

  • (writer)

    ‘self`

Yield Parameters:

Yield Returns:

  • (void)


136
137
138
139
140
# File 'lib/rdf/vocab/writer.rb', line 136

def initialize(output = $stdout, base_uri:, **options, &block)
  @graph = RDF::Repository.new
  options.merge(base_uri: base_uri)
  super
end

Instance Attribute Details

#class_nameObject

Returns the value of attribute class_name.



69
70
71
# File 'lib/rdf/vocab/writer.rb', line 69

def class_name
  @class_name
end

#module_nameObject

Returns the value of attribute module_name.



69
70
71
# File 'lib/rdf/vocab/writer.rb', line 69

def module_name
  @module_name
end

Class Method Details

.optionsObject



71
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
102
103
104
105
106
107
108
109
110
111
112
# File 'lib/rdf/vocab/writer.rb', line 71

def self.options
  [
    RDF::CLI::Option.new(
      symbol: :class_name,
      datatype: String,
      control: :text,
      on: ["--class-name NAME"],
      use: :required,
      description: "Name of created Ruby class (vocabulary format)."),
    RDF::CLI::Option.new(
      symbol: :extra,
      datatype: String,
      control: :none,
      on: ["--extra URIEncodedJSON"],
      description: "URI Encoded JSON representation of extra data"
    ) do |arg|
      ::JSON.parse(::CGI.unescape(arg)).inject({}) do |m1, (term, defs)|
        d1 = defs.inject({}) {|m, (k,v)| m.merge(k.to_sym => v)}
        m1.merge(term.to_sym => d1)
      end
    end,
    RDF::CLI::Option.new(
      symbol: :module_name,
      datatype: String,
      control: :text,
      on: ["--module-name NAME"],
      description: "Name of Ruby module containing class-name (vocabulary format)."),
    RDF::CLI::Option.new(
      symbol: :noDoc,
      datatype: TrueClass,
      control: :checkbox,
      on: ["--noDoc"],
      description: "Do not output Yard documentation."),
    RDF::CLI::Option.new(
      symbol: :strict,
      datatype: TrueClass,
      control: :checkbox,
      on: ["--strict"],
      description: "Make strict vocabulary"
    ) {true},
  ]
end

Instance Method Details

#write_epilogueObject

Generate vocabulary



148
149
150
151
152
153
154
155
156
157
158
159
160
161
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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
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
260
261
262
263
264
265
266
267
268
269
270
271
# File 'lib/rdf/vocab/writer.rb', line 148

def write_epilogue
  class_name = options[:class_name]
  module_name = options.fetch(:module_name, "RDF")
  source = options.fetch(:location, base_uri)
  strict = options.fetch(:strict, false)

  # Passing a graph for the location causes it to serialize the written triples.
  vocab = RDF::Vocabulary.from_graph(@graph,
                                     url: base_uri,
                                     class_name: class_name,
                                     extra: options[:extra])

  @output.print %(# -*- encoding: utf-8 -*-
    # frozen_string_literal: true
    # This file generated automatically using rdf vocabulary format from #{source}
    require 'rdf'
    module #{module_name}
    ).gsub(/^          /, '')

  if @options[:noDoc]
    @output.print %(  # Vocabulary for <#{base_uri}>
      # @!visibility private
    ).gsub(/^          /, '')
  else
    @output.print %(  # @!parse
      #   # Vocabulary for <#{base_uri}>
      #   #
    ).gsub(/^          /, '')
  end

  if vocab.ontology && !@options[:noDoc]
    ont_doc = []
    %i(
      http://purl.org/dc/terms/title
      http://purl.org/dc/elements/1.1/title
      label
      comment
      http://purl.org/dc/terms/description
      http://purl.org/dc/elements/1.1/description
    ).each do |attr|
      next unless vocab.ontology.attributes[attr]
      Array(vocab.ontology.attributes[attr]).each do |v|
        ont_doc << "  #   # " + v.to_s.gsub(/\s+/, ' ')
      end
    end
    @output.puts ont_doc.join("\n  #   #\n") unless ont_doc.empty?
    # Version Info
    # See Also
    Array(vocab.ontology.attributes[:'http://www.w3.org/2002/07/owl#versionInfo']).each do |vers|
      @output.puts "  #   # @version #{vers}"
    end
    # See Also
    Array(vocab.ontology.attributes[:'http://www.w3.org/2000/01/rdf-schema#seeAlso']).each do |see|
      @output.puts "  #   # @see #{see}"
    end
  end
  @output.puts %(  #   class #{class_name} < RDF::#{"Strict" if strict}Vocabulary) unless @options[:noDoc]

  # Split nodes into Class/Property/Datatype/Other
  term_nodes = {
    ontology: {},
    class: {},
    property: {},
    datatype: {},
    other: {}
  }

  # Generate Ontology first
  if vocab.ontology
    term_nodes[:ontology][vocab.ontology.to_s] = vocab.ontology.attributes
  end

  vocab.each.to_a.sort.each do |term|
    name = term.to_s[base_uri.length..-1].to_sym
    next if name.to_s.empty?  # Ontology serialized separately
    kind = begin
      case term.type.to_s
      when /Class/    then :class
      when /Property/ then :property
      when /Datatype/ then :datatype
      else                 :other
      end
    rescue KeyError
      # This can try to resolve referenced terms against the previous version of this vocabulary, which may be strict, and fail if the referenced term hasn't been created yet.
      :other
    end
    term_nodes[kind][name] = term.attributes
  end

  # Yard attribute information for terms
  term_nodes.each do |tt, ttv|
    next if tt == :ontology
    ttv.each do |name, attributes|
      # Only document terms that can be accessed like a Ruby attribute
      next unless name.to_s.match?(/^[_[:alpha:]](?:\w*)[!?=]?$/)
      @output.puts(Array(attributes[:comment]).map do |comment|
        "  #     # #{comment.to_s.gsub(/\s+/, ' ')}"
      end.join("\n  #     #\n")) if attributes[:comment]
      @output.puts "  #     # @return [RDF::Vocabulary::Term]"
      @output.puts "  #     attr_reader :#{name}"
      @output.puts "  #"
    end
  end unless @options[:noDoc]

  # End of yard preamble
  @output.puts "  #   end" unless @options[:noDoc]
  @output.puts %(  #{class_name} = Class.new(RDF::#{"Strict" if strict}Vocabulary("#{base_uri}")) do)

  # Output term definitions
  {
    ontology: "Ontology definition",
    class: "Class definitions",
    property: "Property definitions",
    datatype: "Datatype definitions",
    other: "Extra definitions"
  }.each do |tt, comment|
    next if term_nodes[tt].empty?
    @output.puts "\n    # #{comment}"
    term_nodes[tt].each {|name, attributes| from_node name, attributes, tt}
  end

  # Query the vocabulary to extract property and class definitions
  @output.puts "  end\nend"
end

#write_triple(subject, predicate, object) ⇒ Object



142
143
144
# File 'lib/rdf/vocab/writer.rb', line 142

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