Class: RDF::Vocabulary

Inherits:
Object show all
Extended by:
Enumerable
Defined in:
vendor/bundler/ruby/3.3.0/bundler/gems/rdf-884e3ef78084/lib/rdf/vocabulary.rb,
vendor/bundler/ruby/3.3.0/bundler/gems/rdf-884e3ef78084/lib/rdf/vocab/writer.rb,
vendor/bundler/ruby/3.3.0/bundler/gems/rdf-vocab-27503bb35c2b/lib/rdf/vocab/extensions.rb

Overview

A Vocabulary represents an RDFS or OWL vocabulary.

A Vocabulary can also serve as a Domain Specific Language (DSL) for generating an RDF Graph definition for the vocabulary (see #to_enum).

Defining a vocabulary using the DSL

Vocabularies can be defined based on Vocabulary or StrictVocabulary using a simple Domain Specific Language (DSL).

  • Ontology information for the vocabulary itself can be specified using the Vocabulary.ontology method.
  • Terms of the vocabulary are specified using either property or term (alias), with the attributes of the term listed in a hash. See Vocabulary.property for description of the hash. Term attributes become properties of the associated Term (see Term#attributes).

Note that, by default, the prefix associated with the vocabulary for forming and interpreting PNames is created from the class name of the vocabulary. See Vocabulary.__prefix__= for overriding this at runtime.

The simplest way to generate a DSL representation of a vocabulary is using Writer given an Graph representation of the vocabulary.

Vocabularies:

The following vocabularies are pre-defined for your convenience:

  • RDF - Resource Description Framework (RDF)
  • OWL - Web Ontology Language (OWL)
  • RDFS - RDF Schema (RDFS)
  • XSD - XML Schema (XSD)

Other vocabularies are defined in the rdf-vocab gem

Examples:

Using pre-defined RDF vocabularies

include RDF

RDF.type      #=> RDF::URI("http://www.w3.org/1999/02/22-rdf-syntax-ns#type")
RDFS.seeAlso  #=> RDF::URI("http://www.w3.org/2000/01/rdf-schema#seeAlso")
OWL.sameAs    #=> RDF::URI("http://www.w3.org/2002/07/owl#sameAs")
XSD.dateTime  #=> RDF::URI("http://www.w3.org/2001/XMLSchema#dateTime")

Using ad-hoc RDF vocabularies

foaf = RDF::Vocabulary.new("http://xmlns.com/foaf/0.1/")
foaf.knows    #=> RDF::URI("http://xmlns.com/foaf/0.1/knows")
foaf[:name]   #=> RDF::URI("http://xmlns.com/foaf/0.1/name")
foaf['mbox']  #=> RDF::URI("http://xmlns.com/foaf/0.1/mbox")

Defining a simple vocabulary

EX = Class.new(RDF::StrictVocabulay("http://example/ns#")) do
  # Ontology definition
  ontology :"http://example/ns#",
    label: "The RDF Example Vocablary",
    type: "http://www.w3.org/2002/07/owl#Ontology"

  # Class definitions
  term :Class,
    label: "My Class",
    comment: "Good to use as an example",
    type: "rdfs:Class",
    subClassOf: "http://example/SuperClass",
    "ex:prop": "Some annotation property not having a shortcut"

  # Property definitions
  property :prop,
    comment: "A description of the property",
    label: "property",
    domain: "http://example/ns#Class",
    range: "rdfs:Literal",
    isDefinedBy: %(ex:),
    type: "rdf:Property"
end

Method calls are converted to the typical RDF camelcase convention

foaf = RDF::Vocabulary.new("http://xmlns.com/foaf/0.1/")
foaf.family_name    #=> RDF::URI("http://xmlns.com/foaf/0.1/familyName")
owl.same_as         #=> RDF::URI("http://www.w3.org/2002/07/owl#sameAs")
# []-style access is left as is
foaf['family_name'] #=> RDF::URI("http://xmlns.com/foaf/0.1/family_name")
foaf[:family_name]  #=> RDF::URI("http://xmlns.com/foaf/0.1/family_name")

Generating RDF from a vocabulary definition

graph = RDF::Graph.new << RDF::RDFS.to_enum
graph.dump(:ntriples)

See Also:

Defined Under Namespace

Modules: Term, VocabFormatExtensions Classes: Format, Writer

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(uri) ⇒ Vocabulary

Returns a new instance of Vocabulary.

Parameters:



673
674
675
676
677
678
# File 'vendor/bundler/ruby/3.3.0/bundler/gems/rdf-884e3ef78084/lib/rdf/vocabulary.rb', line 673

def initialize(uri)
  @uri = case uri
    when RDF::URI then uri.to_s
    else RDF::URI.parse(uri.to_s) ? uri.to_s : nil
  end
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(property, *args, &block) ⇒ Object (protected)



723
724
725
726
727
728
729
730
731
732
# File 'vendor/bundler/ruby/3.3.0/bundler/gems/rdf-884e3ef78084/lib/rdf/vocabulary.rb', line 723

def method_missing(property, *args, &block)
  property = self.class.camelize(property.to_s)
  if %w(to_ary).include?(property.to_s)
    super
  elsif args.empty?
    self[property]
  else
    super
  end
end

Class Method Details

.[](property) ⇒ RDF::URI

Returns the URI for the term property in this vocabulary.

Parameters:

Returns:



405
406
407
408
409
410
411
# File 'vendor/bundler/ruby/3.3.0/bundler/gems/rdf-884e3ef78084/lib/rdf/vocabulary.rb', line 405

def [](property)
  if props.key?(property.to_sym)
    props[property.to_sym]
  else
    Term.intern([to_s, property.to_s].join(''), vocab: self, attributes: {})
  end
end

.__prefix__Symbol

Returns a suggested vocabulary prefix for this vocabulary class.

Returns:

Since:

  • 0.3.0



609
610
611
612
613
# File 'vendor/bundler/ruby/3.3.0/bundler/gems/rdf-884e3ef78084/lib/rdf/vocabulary.rb', line 609

def __prefix__
  instance_variable_defined?(:@__prefix__) ?
    @__prefix__ :
    __name__.split('::').last.downcase.to_sym
end

.__prefix__=(prefix) ⇒ Symbol

Sets the vocabulary prefix to use for this vocabulary..

Examples:

Overriding a standard vocabulary prefix.

RDF::Vocab::DC.__prefix__ = :dcterms
RDF::Vocab::DC.title.pname #=> 'dcterms:title'

Parameters:

Returns:

Since:

  • 3.2.3



625
626
627
628
629
630
# File 'vendor/bundler/ruby/3.3.0/bundler/gems/rdf-884e3ef78084/lib/rdf/vocabulary.rb', line 625

def __prefix__=(prefix)
  params = RDF::Vocabulary.vocab_map[__prefix__]
  @__prefix__ = prefix.to_sym
  RDF::Vocabulary.register(@__prefix__, self, **params)
  @__prefix__
end

._orig_each {|klass| ... } ⇒ Enumerator

Enumerates known RDF vocabulary classes. Enumerates known RDF vocabulary classes.

Yields:

  • (klass)
  • (klass)

Yield Parameters:

  • klass (Class)
  • klass (Class)

Returns:

  • (Enumerator)
  • (Enumerator)


17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'vendor/bundler/ruby/3.3.0/bundler/gems/rdf-vocab-27503bb35c2b/lib/rdf/vocab/extensions.rb', line 17

def each(&block)
  if self.equal?(Vocabulary)
    if instance_variable_defined?(:@vocabs) && @vocabs
      @vocabs.select(&:name).each(&block)
    else
      # This is needed since all vocabulary classes are defined using
      # Ruby's autoloading facility, meaning that `@@subclasses` will be
      # empty until each subclass has been touched or require'd.
      RDF::VOCABS.each { |v, p| RDF.const_get(p[:class_name].to_sym) unless v == :rdf }
      @@subclasses.select(&:name).each(&block)
    end
  else
    __properties__.each(&block)
  end
end

._orig_from_symRDF::Vocabulary

Return the vocabulary based on it's class_name symbol

Parameters:

Returns:



43
44
45
# File 'vendor/bundler/ruby/3.3.0/bundler/gems/rdf-vocab-27503bb35c2b/lib/rdf/vocab/extensions.rb', line 43

def from_sym(sym)
  RDF.const_get(sym.to_sym)
end

.camelize(str) ⇒ Object (protected)



734
735
736
737
738
# File 'vendor/bundler/ruby/3.3.0/bundler/gems/rdf-884e3ef78084/lib/rdf/vocabulary.rb', line 734

def self.camelize(str)
  str.split('_').inject([]) do |buffer, e| 
    buffer.push(buffer.empty? ? e : e.capitalize)
  end.join
end

.each {|klass| ... } ⇒ Enumerator

Enumerates known RDF vocabulary classes.

Yields:

  • (klass)

Yield Parameters:

  • klass (Class)

Returns:

  • (Enumerator)


93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
# File 'vendor/bundler/ruby/3.3.0/bundler/gems/rdf-884e3ef78084/lib/rdf/vocabulary.rb', line 93

def each(&block)
  if self.equal?(Vocabulary)
    if instance_variable_defined?(:@vocabs) && @vocabs
      @vocabs.select(&:name).each(&block)
    else
      # This is needed since all vocabulary classes are defined using
      # Ruby's autoloading facility, meaning that `@@subclasses` will be
      # empty until each subclass has been touched or require'd.
      RDF::VOCABS.each { |v, p| RDF.const_get(p[:class_name].to_sym) unless v == :rdf }
      @@subclasses.select(&:name).each(&block)
    end
  else
    __properties__.each(&block)
  end
end

.each_statement {|| ... } ⇒ Object

Enumerate each statement constructed from the defined vocabulary terms

If a property value is known to be a URI, or expands to a URI, the object is a URI, otherwise, it will be a Literal.

Yields:

  • statement

Yield Parameters:



468
469
470
471
472
473
474
475
# File 'vendor/bundler/ruby/3.3.0/bundler/gems/rdf-884e3ef78084/lib/rdf/vocabulary.rb', line 468

def each_statement(&block)
  props.each do |name, subject|
    subject.each_statement(&block)
  end

  # Also include the ontology, if it's not also a property
  @ontology.each_statement(&block) if self.ontology && self.ontology != self
end

.enum_for(method = :each_statement, *args) ⇒ RDF::Enumerable::Enumerator Also known as: to_enum

Return an enumerator over Statement defined for this vocabulary.

Returns:

See Also:

  • Object#enum_for


452
453
454
455
456
457
458
# File 'vendor/bundler/ruby/3.3.0/bundler/gems/rdf-884e3ef78084/lib/rdf/vocabulary.rb', line 452

def enum_for(method = :each_statement, *args)
  # Ensure that enumerators are, themselves, queryable
  this = self
  Enumerable::Enumerator.new do |yielder|
    this.send(method, *args) {|*y| yielder << (y.length > 1 ? y : y.first)}
  end
end

.expand_pname(pname) ⇒ Term

Attempt to expand a Compact IRI/PName using loaded vocabularies

The local-part of the PName will will have reserved character escapes unescaped.

Parameters:

Returns:

Raises:

  • (KeyError)

    if pname suffix not found in identified vocabulary.

  • (ArgumentError)

    if resulting URI is not valid



346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
# File 'vendor/bundler/ruby/3.3.0/bundler/gems/rdf-884e3ef78084/lib/rdf/vocabulary.rb', line 346

def expand_pname(pname)
  return pname unless pname.is_a?(String) || pname.is_a?(Symbol)
  prefix, suffix = pname.to_s.split(":", 2)
  # Unescape escaped PN_ESCAPE_CHARS
  if suffix.match?(RDF::URI::PN_ESCAPES)
    suffix = suffix.gsub(RDF::URI::PN_ESCAPES) {|matched| matched[1..-1]}
  end
  if prefix == "rdf"
    RDF[suffix]
  elsif vocab_detail = RDF::Vocabulary.vocab_map[prefix.to_sym]
    vocab = vocab_detail[:class] ||
      RDF::Vocabulary.from_sym(vocab_detail[:class_name])
    suffix.to_s.empty? ? vocab.to_uri : vocab[suffix]
  else
    (RDF::Vocabulary.find_term(pname) rescue nil) || RDF::URI(pname, validate: true)
  end
end

.find(uri) ⇒ Vocabulary

Return the Vocabulary associated with a URI. Allows the trailing '/' or '#' to be excluded

Parameters:

Returns:



369
370
371
372
373
374
375
376
377
378
379
# File 'vendor/bundler/ruby/3.3.0/bundler/gems/rdf-884e3ef78084/lib/rdf/vocabulary.rb', line 369

def find(uri)
  uri = RDF::URI(uri) if uri.is_a?(String)
  return nil unless uri.uri? && uri.valid?
  RDF::Vocabulary.detect do |v|
    if uri.length >= v.to_uri.length
      uri.start_with?(v.to_uri)
    else
      v.to_uri.to_s.sub(%r([/#]$), '') == uri.to_s
    end
  end
end

.find_term(uri) ⇒ Vocabulary::Term

Return the Vocabulary term associated with a URI

Parameters:

  • uri (RDF::URI, String)

    If uri has is a pname in a locded vocabulary, the suffix portion of the PName will have escape characters unescaped before resolving against the vocabulary.

Returns:



387
388
389
390
391
392
393
394
395
396
397
398
# File 'vendor/bundler/ruby/3.3.0/bundler/gems/rdf-884e3ef78084/lib/rdf/vocabulary.rb', line 387

def find_term(uri)
  uri = RDF::URI(uri)
  return uri if uri.is_a?(Vocabulary::Term)
  if vocab = find(uri)
    if vocab.ontology == uri
      vocab.ontology
    else
      suffix = uri.to_s[vocab.to_uri.to_s.length..-1].to_s
      vocab[suffix]
    end
  end
end

.from_graph(graph, url: nil, class_name: nil, extra: nil) ⇒ RDF::Vocabulary

Create a vocabulary from a graph or enumerable

Parameters:

  • graph (RDF::Enumerable)
  • url (URI, #to_s) (defaults to: nil)
  • class_name (RDF::Vocabulary, String) (defaults to: nil)

    The class_name associated with the vocabulary, used for creating the class name of the vocabulary. This will create a new class named with a top-level constant based on class_name. If given an existing vocabulary, it replaces the existing definitions for that vocabulary with those from the graph.

  • extra (Array<Symbol>, Hash{Symbol => Hash}) (defaults to: nil)

    Extra terms to add to the vocabulary. In the first form, it is an array of symbols, for which terms are created. In the second, it is a Hash mapping symbols to property attributes, as described in property.

Returns:



495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
# File 'vendor/bundler/ruby/3.3.0/bundler/gems/rdf-884e3ef78084/lib/rdf/vocabulary.rb', line 495

def from_graph(graph, url: nil, class_name: nil, extra: nil)
  vocab = case class_name
  when RDF::Vocabulary
    class_name.instance_variable_set(:@ontology, nil)
    class_name.instance_variable_set(:@properties, nil)
    class_name
  when String
    Object.const_set(class_name, Class.new(self.create(url)))
  else
    Class.new(self.create(url))
  end

  ont_url = url.to_s.sub(%r([/#]$), '')
  term_defs = {}
  embedded_defs = {}
  graph.each do |statement|
    #next unless statement.subject.uri?
    if statement.subject.start_with?(url) || statement.subject == ont_url
      name = statement.subject.to_s[url.to_s.length..-1].to_s
      term = (term_defs[name.to_sym] ||= {})
    else
      # subject is not a URI or is not associated with the vocabulary
      term = (embedded_defs[statement.subject] ||= {})
    end

    key = Term::URI_ATTRs.fetch(statement.predicate) do
      statement.predicate.to_s.to_sym
    end

    (term[key] ||= []) << statement.object
  end

  # Create extra terms
  term_defs = case extra
  when Array
    extra.inject({}) {|memo, s| memo[s.to_sym] = {}; memo}.merge(term_defs)
  when Hash
    extra.merge(term_defs)
  else
    term_defs
  end

  # Pass over embedded_defs with anonymous references, once
  embedded_defs.each do |term, attributes|
    attributes.each do |ak, avs|
      # Turn embedded BNodes into either their Term definition or a List
      avs = [avs] unless avs.is_a?(Array)
      attributes[ak] = avs.map do |av|
        l = RDF::List.new(subject: av, graph: graph)
        if l.valid?
          RDF::List.new(subject: av) do |nl|
            l.each do |lv|
              nl << (embedded_defs[lv] ? Term.new(vocab: vocab, attributes: embedded_defs[lv]) : lv)
            end
          end
        elsif av.is_a?(RDF::Node)
          Term.new(vocab: vocab, attributes: embedded_defs[av]) if embedded_defs[av]
        else
          av
        end
      end.compact
    end
  end

  term_defs.each do |term, attributes|
    # Turn embedded BNodes into either their Term definition or a List
    attributes.each do |ak, avs|
      attributes[ak] = avs.is_a?(Array) ? (avs.map do |av|
        l = RDF::List.new(subject: av, graph: graph)
        if l.valid?
          RDF::List.new(subject: av) do |nl|
            l.each do |lv|
              nl << (embedded_defs[lv] ? Term.new(vocab: vocab, attributes: embedded_defs[lv]) : lv)
            end
          end
        elsif av.is_a?(RDF::Node)
          Term.new(vocab: vocab, attributes: embedded_defs[av]) if embedded_defs[av]
        else
          av
        end
      end).compact : avs
    end

    if term == :""
      vocab.__ontology__ vocab, attributes
    else
      vocab.__property__ term, attributes
    end
  end

  vocab
end

.from_sym(sym) ⇒ RDF::Vocabulary

Return the vocabulary based on it's class_name symbol

Parameters:

Returns:



126
127
128
# File 'vendor/bundler/ruby/3.3.0/bundler/gems/rdf-884e3ef78084/lib/rdf/vocabulary.rb', line 126

def from_sym(sym)
  RDF.const_get(sym.to_sym)
end

.imported_fromArray<RDF::Vocabulary>

List of vocabularies which import this vocabulary

Returns:



431
432
433
434
435
# File 'vendor/bundler/ruby/3.3.0/bundler/gems/rdf-884e3ef78084/lib/rdf/vocabulary.rb', line 431

def imported_from
  @imported_from ||= begin
    RDF::Vocabulary.select {|v| v.__imports__.include?(self)}
  end
end

.importsArray<RDF::Vocabulary> Also known as: __imports__

Note:

the alias <strong>imports</strong> guards against RDF::OWL.imports returning a term, rather than an array of vocabularies

List of vocabularies this vocabulary owl:imports

Returns:



418
419
420
421
422
423
424
425
# File 'vendor/bundler/ruby/3.3.0/bundler/gems/rdf-884e3ef78084/lib/rdf/vocabulary.rb', line 418

def imports
  return [] unless self.ontology
  @imports ||= begin
    Array(self.ontology.properties[:"http://www.w3.org/2002/07/owl#imports"]).compact
  rescue KeyError
    []
  end
end

.inspectString

Returns a developer-friendly representation of this vocabulary class.

Returns:



592
593
594
595
596
597
598
# File 'vendor/bundler/ruby/3.3.0/bundler/gems/rdf-884e3ef78084/lib/rdf/vocabulary.rb', line 592

def inspect
  if self == Vocabulary
    self.to_s
  else
    sprintf("%s(%s)", superclass.to_s, to_s)
  end
end

.limit_vocabs(*vocabs) ⇒ Array<RDF::Vocabulary>

Limits iteration over vocabularies to just those selected

Examples:

limit to set of vocabularies by symbol

RDF::Vocabulary.limit_vocabs(:rdf, :rdfs, :schema)
RDF::Vocabulary.find_term('http://schema.org/CreativeWork').pname
# => 'schema:CreativeWork'

limit to set of vocabularies by class name

RDF::Vocabulary.limit_vocabs(RDF::RDFV, RDF::RDFS, RDF::Vocab::SCHEMA)
RDF::Vocabulary.find_term('http://schema.org/CreativeWork').pname
# => 'schema:CreativeWork'

Parameters:

  • vocabs (Array<symbol, RDF::Vocabulary>)

    A list of vocabularies (symbols or classes) which may be returned by each. Also limits vocabularies that will be inspeced for other methods. Set to nil, or an empty array to reset.

Returns:



179
180
181
182
183
184
185
186
187
188
189
190
# File 'vendor/bundler/ruby/3.3.0/bundler/gems/rdf-884e3ef78084/lib/rdf/vocabulary.rb', line 179

def limit_vocabs(*vocabs)
  @vocabs = if Array(vocabs).empty?
    nil
  else
    vocabs.map do |vocab|
      vocab = :rdfv if vocab == :rdf
      vocab.is_a?(Symbol) && RDF::VOCABS.key?(vocab) ?
        RDF.const_get(RDF::VOCABS[vocab][:class_name].to_sym) :
        vocab
    end.compact
  end
end

.list(*values) ⇒ RDF::List (protected)

Create a list of terms

Parameters:

  • values (Array<String>)

    Each value treated as a URI or PName

Returns:



656
657
658
# File 'vendor/bundler/ruby/3.3.0/bundler/gems/rdf-884e3ef78084/lib/rdf/vocabulary.rb', line 656

def list(*values)
  RDF::List[*values.map {|v| expand_pname(v) rescue RDF::Literal(v)}]
end

.method_missing(property, *args, &block) ⇒ Object (protected)



643
644
645
646
647
648
649
650
# File 'vendor/bundler/ruby/3.3.0/bundler/gems/rdf-884e3ef78084/lib/rdf/vocabulary.rb', line 643

def method_missing(property, *args, &block)
  property = RDF::Vocabulary.camelize(property.to_s)
  if args.empty? && !to_s.empty?
    Term.intern([to_s, property.to_s].join(''), vocab: self, attributes: {})
  else
    super
  end
end

.ontologyRDF::Vocabulary::Term .ontology(name, options) ⇒ RDF::Vocabulary::Term Also known as: __ontology__

Note:

If the ontology URI has the vocabulary namespace URI as a prefix, it may also be defined using #property or #term

Overloads:



313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
# File 'vendor/bundler/ruby/3.3.0/bundler/gems/rdf-884e3ef78084/lib/rdf/vocabulary.rb', line 313

def ontology(*args)
  case args.length
  when 0
    @ontology if instance_variable_defined?(:@ontology)
  else
    uri, options = args
    URI.cache.delete(uri.to_s.to_sym)  # Clear any previous entry
    # Term attributes passed in a block for lazy evaluation. This helps to avoid load-time circular dependencies
    @ontology = Term.intern(uri.to_s, vocab: self, attributes: options || {})

    # If the URI is the same as the vocabulary namespace, also define it as a term
    props[:""] ||= @ontology if self.to_s == uri.to_s

    @ontology
  end
end

.propertiesObject Also known as: __properties__

@return [ArrayRDF::URI] a list of properties in the current vocabulary



333
334
335
# File 'vendor/bundler/ruby/3.3.0/bundler/gems/rdf-884e3ef78084/lib/rdf/vocabulary.rb', line 333

def properties
  props.values
end

.propertyRDF::Vocabulary::Term .property(name, options) ⇒ RDF::Vocabulary::Term Also known as: term, __property__

Overloads:

  • .propertyRDF::Vocabulary::Term

    Returns property in the current vocabulary

  • .property(name, options) ⇒ RDF::Vocabulary::Term

    Defines a new property or class in the vocabulary as a Term.

    Examples:

    A simple term definition

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

    A term definition with tagged values

    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"

    A SKOS term with anonymous values

    term: :af,
      type: "jur:Country",
      isDefinedBy: "http://eulersharp.sourceforge.net/2003/03swap/countries#",
      "skos:exactMatch": [
        Term.new(
          type: "skos:Concept",
          inScheme: "iso3166-1-alpha-2",
          notation: "ax"),
        Term.new(
          type: "skos:Concept",
          inScheme: "iso3166-1-alpha-3",
          notation: "ala")
      ],
      "foaf:name": "Aland Islands"

    Parameters:

    • name (String, #to_s)
    • options (Hash{Symbol=>String,Array<String>})

      Any other values are expected to expands to a URI using built-in vocabulary prefixes. The value is a String, 'HashSymbol=>String,Array<String>' or Array<String,Hash{Symbol=>Array<String>}> which is interpreted according to the range of the associated property and by heuristically determining the value datatype. See attributes argument to #initialize.

    Returns:



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
272
# File 'vendor/bundler/ruby/3.3.0/bundler/gems/rdf-884e3ef78084/lib/rdf/vocabulary.rb', line 245

def property(*args)
  case args.length
  when 0
    Term.intern("#{self}property", vocab: self, attributes: {})
  else
    name = args.shift unless args.first.is_a?(Hash)
    options = args.last
    if name
      uri_str = [to_s, name.to_s].join('')
      URI.cache.delete(uri_str.to_sym)  # Clear any previous entry

      # Term attributes passed in a block for lazy evaluation. This helps to avoid load-time circular dependencies
      prop = Term.intern(uri_str, vocab: self, attributes: options || {})
      props[name.to_sym] = prop

      # If name is empty, also treat it as the ontology
      @ontology ||= prop if name.to_s.empty?

      # Define an accessor, except for problematic properties
      (class << self; self; end).send(:define_method, name) { prop } unless %w(property term hash).include?(name.to_s)
    else
      # Define the term without a name
      # Term attributes passed in a block for lazy evaluation. This helps to avoid load-time circular dependencies
      prop = Term.new(vocab: self, attributes: options)
    end
    prop
  end
end

.register(prefix, vocab, **params) ⇒ Hash

Register a vocabulary for internal prefix lookups. Parameters of interest include :uri, :class_name, :source, and :skip.

Parameters:

  • prefix (Symbol)

    the prefix to use

  • vocab (String, Class)

    either the URI or the vocab class

  • params (Hash{Symbol => String})

    Relevant parameters

Returns:

  • (Hash)

    The parameter hash, but frozen

Raises:

  • (ArgumentError)


138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
# File 'vendor/bundler/ruby/3.3.0/bundler/gems/rdf-884e3ef78084/lib/rdf/vocabulary.rb', line 138

def register(prefix, vocab, **params)
  # check the input
  raise ArgumentError, "#{prefix} must be symbol-able" unless
    [String, Symbol].any? { |c| prefix.is_a? c }

  # note an explicit uri: param overrides
  case vocab
  when String then params[:uri] ||= vocab
  when Class
    raise ArgumentError, 'vocab must be an RDF::(Strict)Vocabulary' unless
      vocab.ancestors.include? RDF::Vocabulary
    params[:class] = vocab
    params[:uri] ||= vocab.to_uri.to_s
  end

  # fill in the class name
  params[:class_name] ||= prefix.to_s.upcase

  # now freeze and assign
  vocab_map[prefix.to_s.to_sym] = params.freeze
end

.strict?Boolean

Is this a strict vocabulary, or a liberal vocabulary allowing arbitrary properties?

Returns:

  • (Boolean)


194
# File 'vendor/bundler/ruby/3.3.0/bundler/gems/rdf-884e3ef78084/lib/rdf/vocabulary.rb', line 194

def strict?; false; end

.to_html(graph: nil, prefixes: nil, jsonld: nil, template: nil) ⇒ String

Generate HTML+RDFa representation, specific to vocabularies. This uses generated JSON-LD and a Haml template.

Parameters:

  • graph (RDF::Queryable) (defaults to: nil)

    Optional graph, otherwise uses statements from vocabulary.

  • prefixes (Hash{#to_sym => String}) (defaults to: nil)

    to add to output

  • jsonld (String, Hash) (defaults to: nil)

    If not provided, the to_jsonld method is used to generate it.

  • template (String) (defaults to: nil)

    The path to a Haml or ERB template used to generate the output using the JSON-LD serialization

Returns:



329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
# File 'vendor/bundler/ruby/3.3.0/bundler/gems/rdf-vocab-27503bb35c2b/lib/rdf/vocab/extensions.rb', line 329

def to_html(graph: nil, prefixes: nil, jsonld: nil, template: nil)
  # Find namespaces used in the vocabulary
  graph = RDF::Graph.new {|g| each_statement {|s| g << s}} if graph.nil? || graph.empty?

  # Get JSON as an object
  json = case jsonld
  when String then ::JSON.parse(File.read jsonld)
  when Hash   then jsonld
  else
    ::JSON.parse(to_jsonld(graph: graph, prefixes: prefixes))
  end
  raise "Expected JSON-LD data within the '@graph' key" unless json.has_key?('@graph')

  template ||= File.expand_path("../../../../etc/template.erb", __FILE__)

  prefixes = vocab_prefixes(graph).merge(prefixes || {})
  prefixes[:owl] = RDF::OWL.to_uri.to_s

  # Make sure ontology is typed
  json['@graph']['@type'] ||= ['owl:Ontology']

  jld_context = ::JSON::LD::Context.new.parse([json['@context'], json['@graph']['@context']])

  # Expand the JSON-LD to normalize accesses
  expanded = ::JSON::LD::API.expand(json).first
  expanded.delete('@reverse')

  # Re-compact keys
  expanded = expanded.inject({}) do |memo, (k, v)|
    term = RDF::Vocabulary.find_term(k)
    k = term.pname if term
    memo.merge(k => v)
  end

  # Normalize label accessors
  expanded['rdfs:label'] ||= %w(dc:title dc11:title skos:prefLabel).inject(nil) do |memo, key|
    memo || expanded[key]
  end || [{'@value' => json['@graph']['@id']}]
  %w(rdfs_classes rdfs_properties rdfs_datatypes rdfs_instances).each do |section|
    next unless json['@graph'][section]
    json['@graph'][section].each do |node|
      node['rdfs:label'] ||= %w(dc:title dc11:title skos:prefLabel).inject do |memo, key|
        memo || node[key]
      end || [{'@value' => node['@id']}]
    end
  end

  # Expand each part separately, as well.
  %w(rdfs_classes rdfs_properties rdfs_datatypes rdfs_instances).each do |section|
    next unless json['@graph'][section]
    expanded_section = ::JSON::LD::API.expand(json['@graph'][section], expandContext: jld_context)
    # Re-compact keys
    expanded[section] = expanded_section.map do |node|
      node.inject({}) do |memo, (k, v)|
        term = RDF::Vocabulary.find_term(k)
        k = term.pname if term
        memo.merge(k => v)
      end
    end
  end

  # Template invoked with expanded JSON-LD with outer object including `rdfs_classes`, `rdfs_properties`, and `rdf_instances` sections.
  case template
  when /.haml$/
    require 'haml'
    haml = if Haml::VERSION >= "6"
      Haml::Template.new {File.read(template)}
    else
     Haml::Engine.new(File.read(template))
    end
    
    haml.render(self, ont: expanded, context: json['@context'], prefixes: prefixes)
  when /.erb$/
    require 'erubis'
    eruby = Erubis::FastEruby.new(File.read(template))
    eruby.evaluate(binding: self, ont: expanded, context: json['@context'], prefixes: prefixes)
  else
    raise "Unknown template type #{template}. Should have '.erb' or '.haml' extension"
  end
end

.to_iriRDF::URI

Returns the base URI for this vocabulary class. For IRI compatibility

Returns:



446
447
448
# File 'vendor/bundler/ruby/3.3.0/bundler/gems/rdf-884e3ef78084/lib/rdf/vocabulary.rb', line 446

def to_uri
  RDF::URI.intern(@@uris[self].to_s)
end

.to_jsonld(graph: nil, prefixes: nil) ⇒ String

Generate JSON-LD representation, specific to vocabularies

Parameters:

  • graph (RDF::Queryable) (defaults to: nil)

    Optional graph, otherwise uses statements from vocabulary.

  • prefixes (Hash{#to_sym => String}) (defaults to: nil)

    to add to output

Returns:



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
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
# File 'vendor/bundler/ruby/3.3.0/bundler/gems/rdf-vocab-27503bb35c2b/lib/rdf/vocab/extensions.rb', line 176

def to_jsonld(graph: nil, prefixes: nil)
  require 'json/ld'

  context = {}
  rdfs_context = ::JSON.parse %({
    "dc:title": {"@container": "@language"},
    "dc:description": {"@container": "@language"},
    "dc:date": {"@type": "xsd:date"},
    "rdfs:comment": {"@container": "@language"},
    "rdfs:domain": {"@type": "@vocab"},
    "rdfs:label": {"@container": "@language"},
    "rdfs:range": {"@type": "@vocab"},
    "rdfs:seeAlso": {"@type": "@id"},
    "rdfs:subClassOf": {"@type": "@vocab"},
    "rdfs:subPropertyOf": {"@type": "@vocab"},
    "schema:domainIncludes": {"@type": "@vocab"},
    "schema:rangeIncludes": {"@type": "@vocab"},
    "owl:equivalentClass": {"@type": "@vocab"},
    "owl:equivalentProperty": {"@type": "@vocab"},
    "owl:oneOf": {"@container": "@list", "@type": "@vocab"},
    "owl:imports": {"@type": "@id"},
    "owl:versionInfo": {"@type": "@id"},
    "owl:inverseOf": {"@type": "@vocab"},
    "owl:unionOf": {"@type": "@vocab", "@container": "@list"},
    "rdfs_classes": {"@reverse": "rdfs:isDefinedBy", "@type": "@id"},
    "rdfs_properties": {"@reverse": "rdfs:isDefinedBy", "@type": "@id"},
    "rdfs_datatypes": {"@reverse": "rdfs:isDefinedBy", "@type": "@id"},
    "rdfs_instances": {"@reverse": "rdfs:isDefinedBy", "@type": "@id"}
  })
  rdfs_classes, rdfs_properties, rdfs_datatypes, rdfs_instances = [], [], [], [], []

  ontology = {
    "@context" => rdfs_context,
    "@id" => to_uri.to_s
  }

  # Find namespaces used in the vocabulary
  graph = RDF::Graph.new {|g| each_statement {|s| g << s}} if graph.nil? || graph.empty?

  prefixes = vocab_prefixes(graph).merge(prefixes || {})
  prefixes.each do |pfx, uri|
    context[pfx.to_s] = uri.to_s unless pfx.to_s.empty?
  end

  # Determine the category for each subject in the vocabulary graph
  cats = subject_categories(graph)

  # Generate term definitions from graph subjects
  cats.values.flatten.each do |term|
    next unless Array(term.qname).length == 2
    context[term.qname.last.to_s] = term.to_uri.to_s
  end

  # Parse the two contexts so we know what terms are in scope
  jld_context = ::JSON::LD::Context.new.parse([context, rdfs_context])

  {
    ont: {
      heading:  "# #{__name__.split('::').last} Vocabulary definition\n",
      bucket:   ontology,
    },
    classes: {
      heading:  "# Class definitions\n",
      bucket:   rdfs_classes,
      rev_prop: "rdfs_classes"
    },
    properties: {
      heading:  "# Property definitions\n",
      bucket:   rdfs_properties,
      rev_prop: "rdfs_properties"
    },
    datatypes: {
      heading:  "# Datatype definitions\n",
      bucket:   rdfs_datatypes,
      rev_prop: "rdfs_datatypes"
    },
    other: {
      heading:  "# Other definitions\n",
      bucket:   rdfs_instances,
      rev_prop: "rdfs_instances"
    }
  }.each do |key, hash|
    next unless cats[key]

    cats[key].each do |subject|
      node = {"@id" => subject.pname}
      po = {}

      # Group predicates with their values
      graph.query({subject: subject}) do |statement|
        # Sanity check this, as these are set to an empty string if not defined.
        next if [RDF::RDFS.label, RDF::RDFS.comment].include?(statement.predicate) && statement.object.to_s.empty?
        po[statement.predicate] ||= []
        po[statement.predicate] << statement.object
      end

      next if po.empty?

      node['@type'] = po.delete(RDF.type).map {|t| jld_context.compact_iri(t, vocab: true)}

      po.each do |predicate, objects|
        term = jld_context.compact_iri(predicate, vocab: true)
        node[term] = if jld_context.container(term).include?('@language')
          lang_map = objects.inject({}) do |memo, o|
            raise "Language-mapped term #{term} with non plain-literal #{o.inspect}" unless o.literal? && o.plain?
            memo.merge(o.language.to_s => o.value)
          end
          # Don't use language map if there's only one entry with no language
          lang_map = lang_map[""] if lang_map.keys == [""]
          [lang_map]
        else
          objects.map do |o|
            expanded_value = jld_context.expand_value(term, o)
            jld_context.compact_value(term, expanded_value)
          end
        end
      end

      node.each do |property, values|
        case values.length
        when 0 then node.delete(property)
        when 1 then node[property] = values.first
        end
      end

      # Either set bucket from node, or append node to bucket
      if hash[:bucket].is_a?(Hash)
        hash[:bucket].merge!(node)
      else
        ontology[hash[:rev_prop]] ||= hash[:bucket]
        hash[:bucket] << node
      end
    end
  end

  # Serialize result
  {
    "@context" => context,
    "@graph" => ontology
  }.to_json(::JSON::LD::JSON_STATE)
rescue LoadError
  # No JSON-LD serialization unless gem loaded
end

.to_sString

Returns a string representation of this vocabulary class.

Returns:



481
482
483
# File 'vendor/bundler/ruby/3.3.0/bundler/gems/rdf-884e3ef78084/lib/rdf/vocabulary.rb', line 481

def to_s
  @@uris.key?(self) ? @@uris[self].to_s : super
end

.to_ttl(graph: nil, prefixes: nil) ⇒ String

Generate Turtle representation, specific to vocabularies

Parameters:

  • graph (RDF::Queryable) (defaults to: nil)

    Optional graph, otherwise uses statements from vocabulary.

  • prefixes (Hash{#to_sym => String}) (defaults to: nil)

    to add to output

Returns:



96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
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
# File 'vendor/bundler/ruby/3.3.0/bundler/gems/rdf-vocab-27503bb35c2b/lib/rdf/vocab/extensions.rb', line 96

def to_ttl(graph: nil, prefixes: nil)
  require 'rdf/turtle'
  output = []

  # Find namespaces used in the vocabulary
  graph = RDF::Graph.new {|g| each_statement {|s| g << s}} if graph.nil? || graph.empty?

  prefixes = vocab_prefixes(graph).merge(prefixes || {})
  pfx_width = prefixes.keys.map(&:to_s).map(&:length).max
  prefixes.each do |pfx, uri|
    output << "@prefix %*s: <%s> .\n" % [pfx_width, pfx, uri]
  end

  # Determine the category for each subject in the vocabulary graph
  cats = subject_categories(graph)

  writer = RDF::Turtle::Writer.new(StringIO.new, prefixes: prefixes)

  {
    ont: {
      heading:  "# #{__name__.split('::').last} Vocabulary definition\n"
    },
    classes: {
      heading:  "# Class definitions\n"
    },
    properties: {
      heading:  "# Property definitions\n"
    },
    datatypes: {
      heading:  "# Datatype definitions\n"
    },
    other: {
      heading:  "# Other definitions\n"
    }
  }.each do |key, hash|
    next unless cats[key]

    output << "\n\n#{hash[:heading]}"

    cats[key].each do |subject|
      po = {}

      # Group predicates with their values
      graph.query({subject: subject}) do |statement|
        # Sanity check this, as these are set to an empty string if not defined.
        next if [RDF::RDFS.label, RDF::RDFS.comment].include?(statement.predicate) && statement.object.to_s.empty?
        po[statement.predicate] ||= []
        po[statement.predicate] << statement.object
      end

      next if po.empty?

      po_list = []
      unless (types = po.delete(RDF.type)).empty?
        po_list << 'a ' + types.map {|o| writer.format_term(o)}.join(", ")
      end

      # Serialize other predicate/objects
      po.each do |predicate, objects|
        resource = predicate.qname ? predicate.pname : "<#{predicate}>"
        po_list << resource + ' ' + objects.map {|o| writer.format_term(o)}.join(", ")
      end

      # Output statements for this subject
      subj = subject.qname ? subject.pname : "<#{subject}>"
      output << "#{subj} " + po_list.join(";\n  ") + "\n  .\n"
    end
  end

  output.join("")
rescue LoadError
  # No Turtle serialization unless gem loaded
end

.to_uriRDF::URI

Returns the base URI for this vocabulary class.

Returns:



441
442
443
# File 'vendor/bundler/ruby/3.3.0/bundler/gems/rdf-884e3ef78084/lib/rdf/vocabulary.rb', line 441

def to_uri
  RDF::URI.intern(@@uris[self].to_s)
end

.value_to_html(property, value, tag) ⇒ Object

Create HTML for values (Helper method, needs to be public)



412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
# File 'vendor/bundler/ruby/3.3.0/bundler/gems/rdf-vocab-27503bb35c2b/lib/rdf/vocab/extensions.rb', line 412

def value_to_html(property, value, tag)
  value.map do |v|
    %(<#{tag} property="#{property}") +
    if v['@value']
      (v['@language'] ? %( lang="#{v['@language']}") : "") +
      (v['@type'] ? %( datatype="#{RDF::URI(v['@type']).pname}") : "") +
      %(>#{v['@value']})
    elsif v['@id']
      %( resource="#{RDF::URI(v['@id']).pname}">#{RDF::URI(v['@id']).pname})
    else
      raise "Unknown value type: #{v.inspect}, #{property}"
    end +
    %(</#{tag}>)
  end.join("\n")
end

.vocab_mapHash{Symbol => Hash{Symbol => String}}

A hash of all vocabularies by prefix showing relevant URI and associated vocabulary Class Name

alias_method :_orig_vocab_map, :vocab_map

Returns:



114
115
116
117
118
119
# File 'vendor/bundler/ruby/3.3.0/bundler/gems/rdf-884e3ef78084/lib/rdf/vocabulary.rb', line 114

def vocab_map
  # Create an initial duplicate of RDF::VOCABS. We want to
  # ensure the hash itself is modifiable but the values are
  # frozen.
  @vocab_map ||= RDF::VOCABS.transform_values(&:freeze)
end

Instance Method Details

#[](property) ⇒ URI

Returns the URI for the term property in this vocabulary.

Parameters:

Returns:



685
686
687
# File 'vendor/bundler/ruby/3.3.0/bundler/gems/rdf-884e3ef78084/lib/rdf/vocabulary.rb', line 685

def [](property)
  Term.intern([to_s, property.to_s].join(''), vocab: self, attributes: {})
end

#inspectString

Returns a developer-friendly representation of this vocabulary.

Returns:



712
713
714
# File 'vendor/bundler/ruby/3.3.0/bundler/gems/rdf-884e3ef78084/lib/rdf/vocabulary.rb', line 712

def inspect
  sprintf("#<%s:%#0x(%s)>", self.class.name, __id__, to_s)
end

#to_sString

Returns a string representation of this vocabulary.

Returns:



704
705
706
# File 'vendor/bundler/ruby/3.3.0/bundler/gems/rdf-884e3ef78084/lib/rdf/vocabulary.rb', line 704

def to_s
  @uri.to_s
end

#to_uriURI Also known as: to_iri

Returns the base URI for this vocabulary.

Returns:



693
694
695
# File 'vendor/bundler/ruby/3.3.0/bundler/gems/rdf-884e3ef78084/lib/rdf/vocabulary.rb', line 693

def to_uri
  RDF::URI.intern(to_s)
end