Class: RDF::Vocabulary::Writer

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

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, #escaped, #flush, for, format, #format_embTriple, #format_list, #format_literal, #format_node, #format_term, #format_uri, #node_id, open, #prefix, #prefixes, #prefixes=, #puts, #quoted, 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?

Methods included from Util::Coercions

#coerce_statements

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)

124
125
126
127
128
# File 'lib/rdf/vocab/writer.rb', line 124

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


57
58
59
# File 'lib/rdf/vocab/writer.rb', line 57

def class_name
  @class_name
end

#module_nameObject

Returns the value of attribute module_name


57
58
59
# File 'lib/rdf/vocab/writer.rb', line 57

def module_name
  @module_name
end

Class Method Details

.optionsObject


59
60
61
62
63
64
65
66
67
68
69
70
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
# File 'lib/rdf/vocab/writer.rb', line 59

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


136
137
138
139
140
141
142
143
144
145
146
147
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
# File 'lib/rdf/vocab/writer.rb', line 136

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(/^          /, '')

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

  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


130
131
132
# File 'lib/rdf/vocab/writer.rb', line 130

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