Class: JSON::LD::Context
- Inherits:
-
Object
- Object
- JSON::LD::Context
- Includes:
- Utils, RDF::Util::Logger
- Defined in:
- lib/json/ld/context.rb
Defined Under Namespace
Classes: TermDefinition
Constant Summary collapse
- PRELOADED =
Preloaded contexts. To avoid runtime context parsing and downloading, contexts may be pre-loaded by implementations.
{}
- ID_NULL_OBJECT =
The following constants are used to reduce object allocations in #create_term_definition below
{ '@id' => nil }.freeze
- NON_TERMDEF_KEYS =
Set.new(%w(@base @direction @language @protected @version @vocab)).freeze
- JSON_LD_10_EXPECTED_KEYS =
Set.new(%w(@container @id @language @reverse @type)).freeze
- JSON_LD_11_EXPECTED_KEYS =
Set.new(%w(@context @direction @index @nest @prefix @protected)).freeze
- JSON_LD_EXPECTED_KEYS =
(JSON_LD_10_EXPECTED_KEYS + JSON_LD_11_EXPECTED_KEYS).freeze
- JSON_LD_10_TYPE_VALUES =
Set.new(%w(@id @vocab)).freeze
- JSON_LD_11_TYPE_VALUES =
Set.new(%w(@json @none)).freeze
- PREFIX_URI_ENDINGS =
Set.new(%w(: / ? # [ ] @)).freeze
- CONTAINERS_GRAPH =
The following constants are used to reduce object allocations in #compact_iri below
%w(@graph@id @graph@id@set).freeze
- CONTAINERS_GRAPH_INDEX =
%w(@graph@index @graph@index@set).freeze
- CONTAINERS_GRAPH_INDEX_INDEX =
%w(@graph@index @graph@index@set @index @index@set).freeze
- CONTAINERS_GRAPH_SET =
%w(@graph @graph@set @set).freeze
- CONTAINERS_ID_TYPE =
%w(@id @id@set @type @set@type).freeze
- CONTAINERS_ID_VOCAB =
%w(@id @vocab @none).freeze
- CONTAINERS_INDEX_SET =
%w(@index @index@set).freeze
- CONTAINERS_LANGUAGE =
%w(@language @language@set).freeze
- CONTAINERS_VALUE =
%w(@value).freeze
- CONTAINERS_VOCAB_ID =
%w(@vocab @id @none).freeze
- RDF_LITERAL_NATIVE_TYPES =
Set.new([RDF::XSD.boolean, RDF::XSD.integer, RDF::XSD.double]).freeze
Instance Attribute Summary collapse
-
#base ⇒ RDF::URI
The base.
-
#context_base ⇒ RDF::URI
Base IRI of the context, if loaded remotely.
-
#default_direction ⇒ "lrt", "rtl"
Default direction.
-
#default_language ⇒ String
Default language.
-
#doc_base ⇒ RDF::URI
readonly
The base.
-
#iri_to_term ⇒ Hash{RDF::URI => String}
Reverse mappings from IRI to term only for terms, not CURIEs XXX.
- #namer ⇒ BlankNodeNamer
-
#options ⇒ Hash{Symbol => Object}
Global options used in generating IRIs.
-
#previous_context ⇒ Context
Previous definition for this context.
-
#property_scoped ⇒ Boolean
Context is property-scoped.
-
#provided_context ⇒ Context
A context provided to us that we can use without re-serializing XXX.
-
#term_definitions ⇒ Hash{String => TermDefinition}
readonly
Term definitions.
-
#vocab ⇒ RDF::URI
Default vocabulary.
Class Method Summary collapse
-
.add_preloaded(url, context = nil, &block) ⇒ Object
Add preloaded context.
-
.alias_preloaded(a, url) ⇒ Object
Alias a previousliy loaded context.
-
.parse(local_context, protected: false, override_protected: false, propagate: true, **options) ⇒ Context
Create a new context by parsing a context.
Instance Method Summary collapse
-
#as_array?(term) ⇒ Boolean
Should values be represented using an array?.
-
#coerce(term) ⇒ RDF::URI, '@id'
Retrieve term coercion.
-
#compact_iri(iri, value: nil, vocab: nil, reverse: false, **options) ⇒ String
Compacts an absolute IRI to the shortest matching term or compact IRI.
-
#compact_value(property, value, **options) ⇒ Hash
Compact a value.
-
#container(term) ⇒ Array<'@index', '@language', '@index', '@set', '@type', '@id', '@graph'>
Retrieve container mapping, add it if ‘value` is provided.
-
#content(term) ⇒ Hash
Retrieve content of a term.
-
#create_term_definition(local_context, term, defined, override_protected: false, protected: false, remote_contexts: [], validate_scoped: true) ⇒ Object
Create Term Definition.
-
#direction(term) ⇒ String
Retrieve the text direction associated with a term, or the default direction otherwise.
- #dup ⇒ Object
-
#empty? ⇒ Boolean
Initial context, without mappings, vocab or default language.
-
#expand_iri(value, documentRelative: false, vocab: false, local_context: nil, defined: nil, as_string: false, **options) ⇒ RDF::Resource, String
Expand an IRI.
-
#expand_value(property, value, useNativeTypes: false, rdfDirection: nil, **options) ⇒ Hash
If active property has a type mapping in the active context set to @id or @vocab, a JSON object with a single member @id whose value is the result of using the IRI Expansion algorithm on value is returned.
-
#find_definition(term) ⇒ Term
Find a term definition.
-
#from_vocabulary(graph) ⇒ self
Build a context from an RDF::Vocabulary definition.
-
#initialize(**options) {|ec| ... } ⇒ Context
constructor
Create new evaluation context.
- #inspect ⇒ Object
-
#language(term) ⇒ String
Retrieve the language associated with a term, or the default language otherwise.
-
#merge(context) ⇒ Context
Merge in a context, creating a new context with updates from ‘context`.
-
#merge!(context) ⇒ self
Update context with definitions from ‘context`.
-
#nest(term) ⇒ String
Retrieve nest of a term.
-
#parse(local_context, remote_contexts: [], protected: false, override_protected: false, propagate: true, validate_scoped: true) ⇒ Context
Create an Evaluation Context.
-
#processingMode(expected = nil) ⇒ String
Retrieve, or check processing mode.
-
#processingMode=(value = nil, **options) ⇒ String
Set processing mode.
-
#propagate=(value, **options) ⇒ Object
Set propagation @note: by the time this is called, the work has already been done.
-
#reverse?(term) ⇒ Boolean
Is this a reverse term.
-
#reverse_term(term) ⇒ Term
Given a term or IRI, find a reverse term definition matching that term.
-
#serialize(**options) ⇒ Hash
Generate @context.
-
#set_mapping(term, value) ⇒ TermDefinition
Set term mapping.
-
#to_rb(*aliases) ⇒ String
Turn this into a source for a new instantiation.
Methods included from Utils
#add_value, #as_array, #as_resource, #blank_node?, #compare_values, #graph?, #has_property, #has_value, #index?, #list?, #node?, #node_or_ref?, #node_reference?, #simple_graph?, #value?
Constructor Details
#initialize(**options) {|ec| ... } ⇒ Context
Create new evaluation context
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 |
# File 'lib/json/ld/context.rb', line 354 def initialize(**) if [:base] @base = @doc_base = RDF::URI([:base]).dup @doc_base.canonicalize! if [:canonicalize] end self.processingMode = [:processingMode] if .has_key?(:processingMode) @term_definitions = {} @iri_to_term = { RDF.to_uri.to_s => "rdf", RDF::XSD.to_uri.to_s => "xsd" } @namer = BlankNodeMapper.new("t") @options = # Load any defined prefixes ([:prefixes] || {}).each_pair do |k, v| next if k.nil? @iri_to_term[v.to_s] = k @term_definitions[k.to_s] = TermDefinition.new(k, id: v.to_s, simple: true, prefix: true) end self.vocab = [:vocab] if [:vocab] self.default_language = [:language] if [:language] =~ /^[a-zA-Z]{1,8}(-[a-zA-Z0-9]{1,8})*$/ @term_definitions = [:term_definitions] if [:term_definitions] #log_debug("init") {"iri_to_term: #{iri_to_term.inspect}"} yield(self) if block_given? end |
Instance Attribute Details
#context_base ⇒ RDF::URI
Returns base IRI of the context, if loaded remotely.
280 281 282 |
# File 'lib/json/ld/context.rb', line 280 def context_base @context_base end |
#default_direction ⇒ "lrt", "rtl"
Default direction
This adds a direction to plain strings that aren’t otherwise coerced
307 308 309 |
# File 'lib/json/ld/context.rb', line 307 def default_direction @default_direction end |
#default_language ⇒ String
Default language
This adds a language to plain strings that aren’t otherwise coerced
301 302 303 |
# File 'lib/json/ld/context.rb', line 301 def default_language @default_language end |
#doc_base ⇒ RDF::URI (readonly)
The base.
277 278 279 |
# File 'lib/json/ld/context.rb', line 277 def doc_base @doc_base end |
#iri_to_term ⇒ Hash{RDF::URI => String}
Returns Reverse mappings from IRI to term only for terms, not CURIEs XXX.
287 288 289 |
# File 'lib/json/ld/context.rb', line 287 def iri_to_term @iri_to_term end |
#options ⇒ Hash{Symbol => Object}
Returns Global options used in generating IRIs.
317 318 319 |
# File 'lib/json/ld/context.rb', line 317 def @options end |
#previous_context ⇒ Context
Previous definition for this context. This is used for rolling back type-scoped contexts.
291 292 293 |
# File 'lib/json/ld/context.rb', line 291 def previous_context @previous_context end |
#property_scoped ⇒ Boolean
Context is property-scoped
295 296 297 |
# File 'lib/json/ld/context.rb', line 295 def property_scoped @property_scoped end |
#provided_context ⇒ Context
Returns A context provided to us that we can use without re-serializing XXX.
320 321 322 |
# File 'lib/json/ld/context.rb', line 320 def provided_context @provided_context end |
#term_definitions ⇒ Hash{String => TermDefinition} (readonly)
Term definitions
284 285 286 |
# File 'lib/json/ld/context.rb', line 284 def term_definitions @term_definitions end |
#vocab ⇒ RDF::URI
Default vocabulary
Sets the default vocabulary used for expanding terms which aren’t otherwise absolute IRIs
314 315 316 |
# File 'lib/json/ld/context.rb', line 314 def vocab @vocab end |
Class Method Details
.add_preloaded(url, context = nil, &block) ⇒ Object
Add preloaded context. In the block form, the context is lazy evaulated on first use.
30 31 32 |
# File 'lib/json/ld/context.rb', line 30 def add_preloaded(url, context = nil, &block) PRELOADED[url.to_s.freeze] = context || block end |
.alias_preloaded(a, url) ⇒ Object
Alias a previousliy loaded context
38 39 40 |
# File 'lib/json/ld/context.rb', line 38 def alias_preloaded(a, url) PRELOADED[a.to_s.freeze] = PRELOADED[url.to_s.freeze] end |
.parse(local_context, protected: false, override_protected: false, propagate: true, **options) ⇒ Context
Create a new context by parsing a context.
334 335 336 |
# File 'lib/json/ld/context.rb', line 334 def self.parse(local_context, protected: false, override_protected: false, propagate: true, **) self.new(**).parse(local_context, protected: false, override_protected: override_protected, propagate: propagate) end |
Instance Method Details
#as_array?(term) ⇒ Boolean
Should values be represented using an array?
1228 1229 1230 1231 1232 |
# File 'lib/json/ld/context.rb', line 1228 def as_array?(term) return true if CONTEXT_CONTAINER_ARRAY_TERMS.include?(term) term = find_definition(term) term && (term.as_set? || term.container_mapping.include?('@list')) end |
#coerce(term) ⇒ RDF::URI, '@id'
Retrieve term coercion
1215 1216 1217 1218 1219 1220 1221 |
# File 'lib/json/ld/context.rb', line 1215 def coerce(term) # Map property, if it's not an RDF::Value # @type is always is an IRI return '@id' if term == RDF.type || term == '@type' term = find_definition(term) term && term.type_mapping end |
#compact_iri(iri, value: nil, vocab: nil, reverse: false, **options) ⇒ String
Compacts an absolute IRI to the shortest matching term or compact IRI
1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 |
# File 'lib/json/ld/context.rb', line 1434 def compact_iri(iri, value: nil, vocab: nil, reverse: false, **) return if iri.nil? iri = iri.to_s if vocab && inverse_context.has_key?(iri) default_language = if self.default_direction "#{self.default_language}_#{self.default_direction}".downcase else (self.default_language || "@none").downcase end containers = [] tl, tl_value = "@language", "@null" containers.concat(CONTAINERS_INDEX_SET) if index?(value) && !graph?(value) # If the value is a JSON Object with the key @preserve, use the value of @preserve. value = value['@preserve'].first if value.is_a?(Hash) && value.has_key?('@preserve') if reverse tl, tl_value = "@type", "@reverse" containers << '@set' elsif list?(value) # if value is a list object, then set type/language and type/language value to the most specific values that work for all items in the list as follows: containers << "@list" unless index?(value) list = value['@list'] common_type = nil common_language = default_language if list.empty? list.each do |item| item_language, item_type = "@none", "@none" if value?(item) if item.has_key?('@direction') item_language = "#{item['@language']}_#{item['@direction']}".downcase elsif item.has_key?('@language') item_language = item['@language'].downcase elsif item.has_key?('@type') item_type = item['@type'] else item_language = "@null" end else item_type = '@id' end common_language ||= item_language if item_language != common_language && value?(item) common_language = '@none' end common_type ||= item_type if item_type != common_type common_type = '@none' end end common_language ||= '@none' common_type ||= '@none' if common_type != '@none' tl, tl_value = '@type', common_type else tl_value = common_language end elsif graph?(value) # Prefer @index and @id containers, then @graph, then @index containers.concat(CONTAINERS_GRAPH_INDEX_INDEX) if index?(value) containers.concat(CONTAINERS_GRAPH) if value.has_key?('@id') # Prefer an @graph container next containers.concat(CONTAINERS_GRAPH_SET) # Lastly, in 1.1, any graph can be indexed on @index or @id, so add if we haven't already containers.concat(CONTAINERS_GRAPH_INDEX) unless index?(value) containers.concat(CONTAINERS_GRAPH) unless value.has_key?('@id') containers.concat(CONTAINERS_INDEX_SET) unless index?(value) containers << '@set' tl, tl_value = '@type', '@id' else if value?(value) # In 1.1, an language map can be used to index values using @none if value.has_key?('@language') && !index?(value) tl_value = value['@language'].downcase tl_value += "_#{value['@direction']}" if value['@direction'] containers.concat(CONTAINERS_LANGUAGE) elsif value.has_key?('@direction') && !index?(value) tl_value = "_#{value['@direction']}" elsif value.has_key?('@type') tl_value = value['@type'] tl = '@type' end else # In 1.1, an id or type map can be used to index values using @none containers.concat(CONTAINERS_ID_TYPE) tl, tl_value = '@type', '@id' end containers << '@set' end containers << '@none' # In 1.1, an index map can be used to index values using @none, so add as a low priority containers.concat(CONTAINERS_INDEX_SET) unless index?(value) # Values without type or language can use @language map containers.concat(CONTAINERS_LANGUAGE) if value?(value) && value.keys == CONTAINERS_VALUE tl_value ||= '@null' preferred_values = [] preferred_values << '@reverse' if tl_value == '@reverse' if (tl_value == '@id' || tl_value == '@reverse') && value.is_a?(Hash) && value.has_key?('@id') t_iri = compact_iri(value['@id'], vocab: true, document_relative: true) if (r_td = term_definitions[t_iri]) && r_td.id == value['@id'] preferred_values.concat(CONTAINERS_VOCAB_ID) else preferred_values.concat(CONTAINERS_ID_VOCAB) end else tl = '@any' if list?(value) && value['@list'].empty? preferred_values.concat([tl_value, '@none'].compact) end preferred_values << '@any' # if containers included `@language` and preferred_values includes something of the form language-tag_direction, add just the _direction part, to select terms that have that direction. if lang_dir = preferred_values.detect {|v| v.include?('_')} preferred_values << '_' + lang_dir.split('_').last end if p_term = select_term(iri, containers, tl, preferred_values) return p_term end end # At this point, there is no simple term that iri can be compacted to. If vocab is true and active context has a vocabulary mapping: if vocab && self.vocab && iri.start_with?(self.vocab) && iri.length > self.vocab.length suffix = iri[self.vocab.length..-1] return suffix unless term_definitions.has_key?(suffix) end # The iri could not be compacted using the active context's vocabulary mapping. Try to create a compact IRI, starting by initializing compact IRI to null. This variable will be used to tore the created compact IRI, if any. candidates = [] term_definitions.each do |term, td| next if td.nil? || td.id.nil? || td.id == iri || !iri.start_with?(td.id) # Skip term if `@prefix` is not true in term definition next unless td.prefix? suffix = iri[td.id.length..-1] ciri = "#{term}:#{suffix}" candidates << ciri unless value && term_definitions.has_key?(ciri) end return candidates.sort.first if !candidates.empty? # If we still don't have any terms and we're using standard_prefixes, # try those, and add to mapping if @options[:standard_prefixes] candidates = RDF::Vocabulary. select {|v| iri.start_with?(v.to_uri.to_s) && iri != v.to_uri.to_s}. map do |v| prefix = v.__name__.to_s.split('::').last.downcase set_mapping(prefix, v.to_uri.to_s) iri.sub(v.to_uri.to_s, "#{prefix}:").sub(/:$/, '') end return candidates.sort.first if !candidates.empty? end # If iri could be confused with a compact IRI using a term in this context, signal an error term_definitions.each do |term, td| next unless iri.to_s.start_with?("#{term}:") && td.prefix? raise JSON::LD::JsonLdError:: IRIConfusedWithPrefix, "Absolute IRI '#{iri}' confused with prefix '#{term}'" end if !vocab # transform iri to a relative IRI using the document's base IRI iri = remove_base(iri) return iri else return iri end end |
#compact_value(property, value, **options) ⇒ Hash
Compact a value
FIXME: revisit the specification version of this.
1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 |
# File 'lib/json/ld/context.rb', line 1729 def compact_value(property, value, **) #log_debug("compact_value") {"property: #{property.inspect}, value: #{value.inspect}"} indexing = index?(value) && container(property).include?('@index') language = language(property) direction = direction(property) result = case when coerce(property) == '@id' && value.has_key?('@id') && (value.keys - %w(@id @index)).empty? # Compact an @id coercion #log_debug("") {" (@id & coerce)"} compact_iri(value['@id']) when coerce(property) == '@vocab' && value.has_key?('@id') && (value.keys - %w(@id @index)).empty? # Compact an @id coercion #log_debug("") {" (@id & coerce & vocab)"} compact_iri(value['@id'], vocab: true) when value.has_key?('@id') #log_debug("") {" (@id)"} # return value as is value when value['@type'] && value['@type'] == coerce(property) # Compact common datatype #log_debug("") {" (@type & coerce) == #{coerce(property)}"} value['@value'] when coerce(property) == '@none' || value['@type'] # use original expanded value value when !value['@value'].is_a?(String) #log_debug("") {" (native)"} indexing || !index?(value) ? value['@value'] : value when value['@language'].to_s.downcase == language.to_s.downcase && value['@direction'] == direction # Compact language and direction indexing || !index?(value) ? value['@value'] : value else value end if result.is_a?(Hash) && result.has_key?('@type') && value['@type'] != '@json' # Compact values of @type c_type = if result['@type'].is_a?(Array) result['@type'].map {|t| compact_iri(t, vocab: true)} else compact_iri(result['@type'], vocab: true) end result = result.merge('@type' => c_type) end # If the result is an object, tranform keys using any term keyword aliases if result.is_a?(Hash) && result.keys.any? {|k| self.alias(k) != k} #log_debug("") {" (map to key aliases)"} new_element = {} result.each do |k, v| new_element[self.alias(k)] = v end result = new_element end #log_debug("") {"=> #{result.inspect}"} result end |
#container(term) ⇒ Array<'@index', '@language', '@index', '@set', '@type', '@id', '@graph'>
Retrieve container mapping, add it if ‘value` is provided
1204 1205 1206 1207 1208 |
# File 'lib/json/ld/context.rb', line 1204 def container(term) return [term] if term == '@list' term = find_definition(term) term ? term.container_mapping : Set.new end |
#content(term) ⇒ Hash
Retrieve content of a term
1239 1240 1241 1242 |
# File 'lib/json/ld/context.rb', line 1239 def content(term) term = find_definition(term) term && term.content end |
#create_term_definition(local_context, term, defined, override_protected: false, protected: false, remote_contexts: [], validate_scoped: true) ⇒ Object
Create Term Definition
Term definitions are created by parsing the information in the given local context for the given term. If the given term is a compact IRI, it may omit an IRI mapping by depending on its prefix having its own term definition. If the prefix is a key in the local context, then its term definition must first be created, through recursion, before continuing. Because a term definition can depend on other term definitions, a mechanism must be used to detect cyclical dependencies. The solution employed here uses a map, defined, that keeps track of whether or not a term has been defined or is currently in the process of being defined. This map is checked before any recursion is attempted.
After all dependencies for a term have been defined, the rest of the information in the local context for the given term is taken into account, creating the appropriate IRI mapping, container mapping, and type mapping or language mapping for the term.
769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 |
# File 'lib/json/ld/context.rb', line 769 def create_term_definition(local_context, term, defined, override_protected: false, protected: false, remote_contexts: [], validate_scoped: true) # Expand a string value, unless it matches a keyword #log_debug("create_term_definition") {"term = #{term.inspect}"} # If defined contains the key term, then the associated value must be true, indicating that the term definition has already been created, so return. Otherwise, a cyclical term definition has been detected, which is an error. case defined[term] when TrueClass then return when nil defined[term] = false else raise JsonLdError::CyclicIRIMapping, "Cyclical term dependency found: #{term.inspect}" end # Initialize value to a the value associated with the key term in local context. value = local_context.fetch(term, false) simple_term = value.is_a?(String) || value.nil? # Since keywords cannot be overridden, term must not be a keyword. Otherwise, an invalid value has been detected, which is an error. if term == '@type' && value.is_a?(Hash) && !value.empty? && processingMode("json-ld-1.1") && (value.keys - %w(@container @protected)).empty? && value.fetch('@container', '@set') == '@set' # thes are the only cases were redefining a keyword is allowed elsif KEYWORDS.include?(term) # TODO anything that looks like a keyword raise JsonLdError::KeywordRedefinition, "term must not be a keyword: #{term.inspect}" if @options[:validate] elsif term.to_s.match?(/^@[a-zA-Z]+$/) && @options[:validate] warn "Terms beginning with '@' are reserved for future use and ignored: #{term}." return elsif !term_valid?(term) && @options[:validate] raise JsonLdError::InvalidTermDefinition, "term is invalid: #{term.inspect}" end value = {'@id' => value} if simple_term # Remove any existing term definition for term in active context. previous_definition = term_definitions[term] if previous_definition && previous_definition.protected? && !override_protected # Check later to detect identical redefinition else term_definitions.delete(term) if previous_definition end raise JsonLdError::InvalidTermDefinition, "Term definition for #{term.inspect} is an #{value.class} on term #{term.inspect}" unless value.is_a?(Hash) #log_debug("") {"Hash[#{term.inspect}] = #{value.inspect}"} definition = TermDefinition.new(term) definition.simple = simple_term expected_keys = case processingMode when "json-ld-1.0" then JSON_LD_10_EXPECTED_KEYS else JSON_LD_EXPECTED_KEYS end # Any of these keys cause us to process as json-ld-1.1, unless otherwise set if processingMode.nil? && value.any? { |key, _| !JSON_LD_11_EXPECTED_KEYS.include?(key) } processingMode('json-ld-11') end if value.any? { |key, _| !expected_keys.include?(key) } extra_keys = value.keys - expected_keys.to_a raise JsonLdError::InvalidTermDefinition, "Term definition for #{term.inspect} has unexpected keys: #{extra_keys.join(', ')}" end # Potentially note that the term is protected definition.protected = value.fetch('@protected', protected) if value.has_key?('@type') type = value['@type'] # SPEC FIXME: @type may be nil type = case type when nil type when String begin (type, vocab: true, documentRelative: false, local_context: local_context, defined: defined) rescue JsonLdError::InvalidIRIMapping raise JsonLdError::InvalidTypeMapping, "invalid mapping for '@type': #{type.inspect} on term #{term.inspect}" end else :error end if JSON_LD_11_TYPE_VALUES.include?(type) && processingMode('json-ld-1.1') # This is okay and used in compaction in 1.1 elsif !JSON_LD_10_TYPE_VALUES.include?(type) && !(type.is_a?(RDF::URI) && type.absolute?) raise JsonLdError::InvalidTypeMapping, "unknown mapping for '@type': #{type.inspect} on term #{term.inspect}" end #log_debug("") {"type_mapping: #{type.inspect}"} definition.type_mapping = type end if value.has_key?('@reverse') raise JsonLdError::InvalidReverseProperty, "unexpected key in #{value.inspect} on term #{term.inspect}" if value.key?('@id') || value.key?('@nest') raise JsonLdError::InvalidIRIMapping, "expected value of @reverse to be a string: #{value['@reverse'].inspect} on term #{term.inspect}" unless value['@reverse'].is_a?(String) if value['@reverse'].to_s.match?(/^@[a-zA-Z]+$/) && @options[:validate] warn "Values beginning with '@' are reserved for future use and ignored: #{value['@reverse']}." return end # Otherwise, set the IRI mapping of definition to the result of using the IRI Expansion algorithm, passing active context, the value associated with the @reverse key for value, true for vocab, true for document relative, local context, and defined. If the result is not an absolute IRI, i.e., it contains no colon (:), an invalid IRI mapping error has been detected and processing is aborted. definition.id = (value['@reverse'], vocab: true, local_context: local_context, defined: defined) raise JsonLdError::InvalidIRIMapping, "non-absolute @reverse IRI: #{definition.id} on term #{term.inspect}" unless definition.id.is_a?(RDF::Node) || definition.id.is_a?(RDF::URI) && definition.id.absolute? if term[1..-1].to_s.include?(':') && (term_iri = (term)) != definition.id raise JsonLdError::InvalidIRIMapping, "term #{term} expands to #{definition.id}, not #{term_iri}" end warn "[DEPRECATION] Blank Node terms deprecated in JSON-LD 1.1." if @options[:validate] && processingMode('json-ld-1.1') && definition.id.to_s.start_with?("_:") # If value contains an @container member, set the container mapping of definition to its value; if its value is neither @set, @index, @type, @id, an absolute IRI nor null, an invalid reverse property error has been detected (reverse properties only support set- and index-containers) and processing is aborted. if value.has_key?('@container') container = value['@container'] raise JsonLdError::InvalidReverseProperty, "unknown mapping for '@container' to #{container.inspect} on term #{term.inspect}" unless container.is_a?(String) && (container == '@set' || container == '@index') definition.container_mapping = check_container(container, local_context, defined, term) end definition.reverse_property = true elsif value.has_key?('@id') && value['@id'].nil? # Allowed to reserve a null term, which may be protected elsif value.has_key?('@id') && value['@id'] != term raise JsonLdError::InvalidIRIMapping, "expected value of @id to be a string: #{value['@id'].inspect} on term #{term.inspect}" unless value['@id'].is_a?(String) if !KEYWORDS.include?(value['@id'].to_s) && value['@id'].to_s.match?(/^@[a-zA-Z]+$/) && @options[:validate] warn "Values beginning with '@' are reserved for future use and ignored: #{value['@id']}." return end definition.id = (value['@id'], vocab: true, local_context: local_context, defined: defined) raise JsonLdError::InvalidKeywordAlias, "expected value of @id to not be @context on term #{term.inspect}" if definition.id == '@context' if term.match?(/(?::[^:])|\//) term_iri = (term, vocab: true, local_context: local_context, defined: defined.merge(term => true)) if term_iri != definition.id raise JsonLdError::InvalidIRIMapping, "term #{term} expands to #{definition.id}, not #{term_iri}" end end warn "[DEPRECATION] Blank Node terms deprecated in JSON-LD 1.1." if @options[:validate] && processingMode('json-ld-1.1') && definition.id.to_s.start_with?("_:") # If id ends with a gen-delim, it may be used as a prefix for simple terms definition.prefix = true if !term.include?(':') && simple_term && (definition.id.to_s.end_with?(':', '/', '?', '#', '[', ']', '@') || definition.id.to_s.start_with?('_:')) elsif term[1..-1].include?(':') # If term is a compact IRI with a prefix that is a key in local context then a dependency has been found. Use this algorithm recursively passing active context, local context, the prefix as term, and defined. prefix, suffix = term.split(':', 2) create_term_definition(local_context, prefix, defined, protected: protected) if local_context.has_key?(prefix) definition.id = if td = term_definitions[prefix] # If term's prefix has a term definition in active context, set the IRI mapping for definition to the result of concatenating the value associated with the prefix's IRI mapping and the term's suffix. td.id + suffix else # Otherwise, term is an absolute IRI. Set the IRI mapping for definition to term term end #log_debug("") {"=> #{definition.id}"} elsif term.include?('/') # If term is a relative IRI definition.id = (term, vocab: true) raise JsonLdError::InvalidKeywordAlias, "expected term to expand to an absolute IRI #{term.inspect}" unless definition.id.absolute? elsif KEYWORDS.include?(term) # This should only happen for @type when @container is @set definition.id = term else # Otherwise, active context must have a vocabulary mapping, otherwise an invalid value has been detected, which is an error. Set the IRI mapping for definition to the result of concatenating the value associated with the vocabulary mapping and term. raise JsonLdError::InvalidIRIMapping, "relative term definition without vocab: #{term} on term #{term.inspect}" unless vocab definition.id = vocab + term #log_debug("") {"=> #{definition.id}"} end @iri_to_term[definition.id] = term if simple_term && definition.id if value.has_key?('@container') #log_debug("") {"container_mapping: #{value['@container'].inspect}"} definition.container_mapping = check_container(value['@container'], local_context, defined, term) # If @container includes @type if definition.container_mapping.include?('@type') # If definition does not have @type, set @type to @id definition.type_mapping ||= '@id' # If definition includes @type with a value other than @id or @vocab, an illegal type mapping error has been detected if !CONTEXT_TYPE_ID_VOCAB.include?(definition.type_mapping) raise JsonLdError::InvalidTypeMapping, "@container: @type requires @type to be @id or @vocab" end end end if value.has_key?('@index') # property-based indexing raise JsonLdError::InvalidTermDefinition, "@index without @index in @container: #{value['@index']} on term #{term.inspect}" unless definition.container_mapping.include?('@index') raise JsonLdError::InvalidTermDefinition, "@index must expand to an IRI: #{value['@index']} on term #{term.inspect}" unless value['@index'].is_a?(String) && !value['@index'].start_with?('@') definition.index = value['@index'].to_s end if value.has_key?('@context') begin self.parse(value['@context'], override_protected: true, remote_contexts: remote_contexts, validate_scoped: false) # Record null context in array form definition.context = value['@context'] ? value['@context'] : [nil] rescue JsonLdError => e raise JsonLdError::InvalidScopedContext, "Term definition for #{term.inspect} contains illegal value for @context: #{e.}" end end if value.has_key?('@language') language = value['@language'] language = case value['@language'] when String # Warn on an invalid language tag, unless :validate is true, in which case it's an error if value['@language'] !~ /^[a-zA-Z]{1,8}(-[a-zA-Z0-9]{1,8})*$/ warn "@language must be valid BCP47: #{value['@language'].inspect}" end [:lowercaseLanguage] ? value['@language'].downcase : value['@language'] when nil nil else raise JsonLdError::InvalidLanguageMapping, "language must be null or a string, was #{value['@language'].inspect}} on term #{term.inspect}" end #log_debug("") {"language_mapping: #{language.inspect}"} definition.language_mapping = language || false end if value.has_key?('@direction') direction = value['@direction'] raise JsonLdError::InvalidBaseDirection, "direction must be null, 'ltr', or 'rtl', was #{language.inspect}} on term #{term.inspect}" unless direction.nil? || %w(ltr rtl).include?(direction) #log_debug("") {"direction_mapping: #{direction.inspect}"} definition.direction_mapping = direction || false end if value.has_key?('@nest') nest = value['@nest'] raise JsonLdError::InvalidNestValue, "nest must be a string, was #{nest.inspect}} on term #{term.inspect}" unless nest.is_a?(String) raise JsonLdError::InvalidNestValue, "nest must not be a keyword other than @nest, was #{nest.inspect}} on term #{term.inspect}" if nest.match?(/^@[a-zA-Z]+$/) && nest != '@nest' #log_debug("") {"nest: #{nest.inspect}"} definition.nest = nest end if value.has_key?('@prefix') raise JsonLdError::InvalidTermDefinition, "@prefix used on compact or relative IRI term #{term.inspect}" if term.match?(%r{:|/}) case pfx = value['@prefix'] when TrueClass, FalseClass definition.prefix = pfx else raise JsonLdError::InvalidPrefixValue, "unknown value for '@prefix': #{pfx.inspect} on term #{term.inspect}" end raise JsonLdError::InvalidTermDefinition, "keywords may not be used as prefixes" if pfx && KEYWORDS.include?(definition.id.to_s) end if previous_definition && previous_definition.protected? && definition != previous_definition && !override_protected definition = previous_definition raise JSON::LD::JsonLdError::ProtectedTermRedefinition, "Attempt to redefine protected term #{term}" end term_definitions[term] = definition defined[term] = true ensure # Re-build after term definitions set @inverse_context = nil end |
#direction(term) ⇒ String
Retrieve the text direction associated with a term, or the default direction otherwise
1279 1280 1281 1282 1283 |
# File 'lib/json/ld/context.rb', line 1279 def direction(term) term = find_definition(term) dir = term && term.direction_mapping dir.nil? ? @default_direction : (dir == false ? nil : dir) end |
#dup ⇒ Object
1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 |
# File 'lib/json/ld/context.rb', line 1830 def dup # Also duplicate mappings, coerce and list that = self ec = super ec.instance_eval do @term_definitions = that.term_definitions.dup @iri_to_term = that.iri_to_term.dup end ec end |
#empty? ⇒ Boolean
Initial context, without mappings, vocab or default language
389 390 391 |
# File 'lib/json/ld/context.rb', line 389 def empty? @term_definitions.empty? && self.vocab.nil? && self.default_language.nil? end |
#expand_iri(value, documentRelative: false, vocab: false, local_context: nil, defined: nil, as_string: false, **options) ⇒ RDF::Resource, String
Expand an IRI. Relative IRIs are expanded against any document base.
1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 |
# File 'lib/json/ld/context.rb', line 1332 def (value, documentRelative: false, vocab: false, local_context: nil, defined: nil, as_string: false, ** ) return (value && as_string ? value.to_s : value) unless value.is_a?(String) return value if KEYWORDS.include?(value) return nil if value.match?(/^@[a-zA-Z]+$/) defined = defined || {} # if we initialized in the keyword arg we would allocate {} at each invokation, even in the 2 (common) early returns above. # If local context is not null, it contains a key that equals value, and the value associated with the key that equals value in defined is not true, then invoke the Create Term Definition subalgorithm, passing active context, local context, value as term, and defined. This will ensure that a term definition is created for value in active context during Context Processing. if local_context && local_context.has_key?(value) && !defined[value] create_term_definition(local_context, value, defined) end if (v_td = term_definitions[value]) && KEYWORDS.include?(v_td.id) return (as_string ? v_td.id.to_s : v_td.id) end # If active context has a term definition for value, and the associated mapping is a keyword, return that keyword. # If vocab is true and the active context has a term definition for value, return the associated IRI mapping. if (v_td = term_definitions[value]) && (vocab || KEYWORDS.include?(v_td.id)) return (as_string ? v_td.id.to_s : v_td.id) end # If value contains a colon (:), it is either an absolute IRI or a compact IRI: if value[1..-1].to_s.include?(':') prefix, suffix = value.split(':', 2) # If prefix is underscore (_) or suffix begins with double-forward-slash (//), return value as it is already an absolute IRI or a blank node identifier. if prefix == '_' v = RDF::Node.new(namer.get_sym(suffix)) return (as_string ? v.to_s : v) end if suffix.start_with?('//') v = RDF::URI(value) return (as_string ? v.to_s : v) end # If local context is not null, it contains a key that equals prefix, and the value associated with the key that equals prefix in defined is not true, invoke the Create Term Definition algorithm, passing active context, local context, prefix as term, and defined. This will ensure that a term definition is created for prefix in active context during Context Processing. if local_context && local_context.has_key?(prefix) && !defined[prefix] create_term_definition(local_context, prefix, defined) end # If active context contains a term definition for prefix, return the result of concatenating the IRI mapping associated with prefix and suffix. if (td = term_definitions[prefix]) && !td.id.nil? && td.prefix? return (as_string ? td.id.to_s : td.id) + suffix elsif RDF::URI(value).absolute? # Otherwise, if the value has the form of an absolute IRI, return it return (as_string ? value.to_s : RDF::URI(value)) else # Otherwise, it is a relative IRI end end result = if vocab && self.vocab # If vocab is true, and active context has a vocabulary mapping, return the result of concatenating the vocabulary mapping with value. self.vocab + value elsif documentRelative && (base ||= self.base) # Otherwise, if document relative is true, set value to the result of resolving value against the base IRI. Only the basic algorithm in section 5.2 of [RFC3986] is used; neither Syntax-Based Normalization nor Scheme-Based Normalization are performed. Characters additionally allowed in IRI references are treated in the same way that unreserved characters are treated in URI references, per section 6.5 of [RFC3987]. value = RDF::URI(value) value.absolute? ? value : RDF::URI(base).join(value) elsif local_context && RDF::URI(value).relative? # If local context is not null and value is not an absolute IRI, an invalid IRI mapping error has been detected and processing is aborted. raise JSON::LD::JsonLdError::InvalidIRIMapping, "not an absolute IRI: #{value}" else RDF::URI(value) end result && as_string ? result.to_s : result end |
#expand_value(property, value, useNativeTypes: false, rdfDirection: nil, **options) ⇒ Hash
If active property has a type mapping in the active context set to @id or @vocab, a JSON object with a single member @id whose value is the result of using the IRI Expansion algorithm on value is returned.
Otherwise, the result will be a JSON object containing an @value member whose value is the passed value. Additionally, an @type member will be included if there is a type mapping associated with the active property or an @language member if value is a string and there is language mapping associated with the active property.
1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 |
# File 'lib/json/ld/context.rb', line 1630 def (property, value, useNativeTypes: false, rdfDirection: nil, **) #log_debug("expand_value") {"property: #{property.inspect}, value: #{value.inspect}"} td = term_definitions.fetch(property, TermDefinition.new(property)) # If the active property has a type mapping in active context that is @id, return a new JSON object containing a single key-value pair where the key is @id and the value is the result of using the IRI Expansion algorithm, passing active context, value, and true for document relative. if value.is_a?(String) && td.type_mapping == '@id' #log_debug("") {"as relative IRI: #{value.inspect}"} return {'@id' => (value, documentRelative: true).to_s} end # If active property has a type mapping in active context that is @vocab, return a new JSON object containing a single key-value pair where the key is @id and the value is the result of using the IRI Expansion algorithm, passing active context, value, true for vocab, and true for document relative. if value.is_a?(String) && td.type_mapping == '@vocab' #log_debug("") {"as vocab IRI: #{value.inspect}"} return {'@id' => (value, vocab: true, documentRelative: true).to_s} end value = RDF::Literal(value) if value.is_a?(Date) || value.is_a?(DateTime) || value.is_a?(Time) result = case value when RDF::URI, RDF::Node #log_debug("URI | BNode") { value.to_s } {'@id' => value.to_s} when RDF::Literal #log_debug("Literal") {"datatype: #{value.datatype.inspect}"} res = {} if value.datatype == RDF::URI(RDF.to_uri + "JSON") && processingMode('json-ld-1.1') # Value parsed as JSON # FIXME: MultiJson res['@value'] = ::JSON.parse(value.object) res['@type'] = '@json' elsif value.datatype.start_with?("https://www.w3.org/ns/i18n#") && rdfDirection == 'i18n-datatype' && processingMode('json-ld-1.1') lang, dir = value.datatype.fragment.split('_') res['@value'] = value.to_s unless lang.empty? if lang !~ /^[a-zA-Z]{1,8}(-[a-zA-Z0-9]{1,8})*$/ if [:validate] raise JsonLdError::InvalidLanguageMapping, "rdf:language must be valid BCP47: #{lang.inspect}" else warn "rdf:language must be valid BCP47: #{lang.inspect}" end end res['@language'] = lang end res['@direction'] = dir elsif useNativeTypes && RDF_LITERAL_NATIVE_TYPES.include?(value.datatype) res['@value'] = value.object res['@type'] = uri(coerce(property)) if coerce(property) else value.canonicalize! if value.datatype == RDF::XSD.double res['@value'] = value.to_s if coerce(property) res['@type'] = uri(coerce(property)).to_s elsif value.has_datatype? res['@type'] = uri(value.datatype).to_s elsif value.has_language? || language(property) res['@language'] = (value.language || language(property)).to_s # FIXME: direction end end res else # Otherwise, initialize result to a JSON object with an @value member whose value is set to value. res = {'@value' => value} if td.type_mapping && !CONTAINERS_ID_VOCAB.include?(td.type_mapping.to_s) res['@type'] = td.type_mapping.to_s elsif value.is_a?(String) language = language(property) direction = direction(property) res['@language'] = language if language res['@direction'] = direction if direction end res end #log_debug("") {"=> #{result.inspect}"} result rescue ::JSON::ParserError => e raise JSON::LD::JsonLdError::InvalidJsonLiteral, e. end |
#find_definition(term) ⇒ Term
Find a term definition
1195 1196 1197 |
# File 'lib/json/ld/context.rb', line 1195 def find_definition(term) term.is_a?(TermDefinition) ? term : term_definitions[term.to_s] end |
#from_vocabulary(graph) ⇒ self
Build a context from an RDF::Vocabulary definition.
1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 |
# File 'lib/json/ld/context.rb', line 1110 def from_vocabulary(graph) statements = {} ranges = {} # Add term definitions for each class and property not in schema:, and # for those properties having an object range graph.each do |statement| next if statement.subject.node? (statements[statement.subject] ||= []) << statement # Keep track of predicate ranges if [RDF::RDFS.range, RDF::SCHEMA.rangeIncludes].include?(statement.predicate) (ranges[statement.subject] ||= []) << statement.object end end # Add term definitions for each class and property not in vocab, and # for those properties having an object range statements.each do |subject, values| types = values.each_with_object([]) { |v, memo| memo << v.object if v.predicate == RDF.type } is_property = types.any? {|t| t.to_s.include?("Property")} term = subject.to_s.split(/[\/\#]/).last if !is_property # Ignore if there's a default voabulary and this is not a property next if vocab && subject.to_s.start_with?(vocab) # otherwise, create a term definition td = term_definitions[term] = TermDefinition.new(term, id: subject.to_s) else prop_ranges = ranges.fetch(subject, []) # If any range is empty or member of range includes rdfs:Literal or schema:Text next if vocab && prop_ranges.empty? || prop_ranges.include?(RDF::SCHEMA.Text) || prop_ranges.include?(RDF::RDFS.Literal) td = term_definitions[term] = TermDefinition.new(term, id: subject.to_s) # Set context typing based on first element in range case r = prop_ranges.first when RDF::XSD.string if self.default_language td.language_mapping = false end # FIXME: text direction when RDF::XSD.boolean, RDF::SCHEMA.Boolean, RDF::XSD.date, RDF::SCHEMA.Date, RDF::XSD.dateTime, RDF::SCHEMA.DateTime, RDF::XSD.time, RDF::SCHEMA.Time, RDF::XSD.duration, RDF::SCHEMA.Duration, RDF::XSD.decimal, RDF::SCHEMA.Number, RDF::XSD.float, RDF::SCHEMA.Float, RDF::XSD.integer, RDF::SCHEMA.Integer td.type_mapping = r td.simple = false else # It's an object range (includes schema:URL) td.type_mapping = '@id' end end end self end |
#inspect ⇒ Object
1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 |
# File 'lib/json/ld/context.rb', line 1818 def inspect v = %w([Context) v << "base=#{base}" if base v << "vocab=#{vocab}" if vocab v << "processingMode=#{processingMode}" if processingMode v << "default_language=#{default_language}" if default_language v << "default_direction=#{default_direction}" if default_direction v << "previous_context" if previous_context v << "term_definitions[#{term_definitions.length}]=#{term_definitions}" v.join(" ") + "]" end |
#language(term) ⇒ String
Retrieve the language associated with a term, or the default language otherwise
1269 1270 1271 1272 1273 |
# File 'lib/json/ld/context.rb', line 1269 def language(term) term = find_definition(term) lang = term && term.language_mapping lang.nil? ? @default_language : (lang == false ? nil : lang) end |
#merge(context) ⇒ Context
Merge in a context, creating a new context with updates from ‘context`
715 716 717 718 719 |
# File 'lib/json/ld/context.rb', line 715 def merge(context) c = self.dup.merge!(context) c.instance_variable_set(:@term_definitions, context.term_definitions.dup) c end |
#merge!(context) ⇒ self
Update context with definitions from ‘context`
726 727 728 729 730 731 732 733 734 735 736 |
# File 'lib/json/ld/context.rb', line 726 def merge!(context) # FIXME: if new context removes the default language, this won't do anything self.default_language = context.default_language if context.default_language self.vocab = context.vocab if context.vocab self.base = context.base if context.base # Merge in Term Definitions term_definitions.merge!(context.term_definitions) @inverse_context = nil # Re-build after term definitions set self end |
#nest(term) ⇒ String
Retrieve nest of a term. value of nest must be @nest or a term that resolves to @nest
1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 |
# File 'lib/json/ld/context.rb', line 1251 def nest(term) term = find_definition(term) if term case term.nest when '@nest', nil term.nest else nest_term = find_definition(term.nest) raise JsonLdError::InvalidNestValue, "nest must a term resolving to @nest, was #{nest_term.inspect}" unless nest_term && nest_term.id == '@nest' term.nest end end end |
#parse(local_context, remote_contexts: [], protected: false, override_protected: false, propagate: true, validate_scoped: true) ⇒ Context
Create an Evaluation Context
When processing a JSON-LD data structure, each processing rule is applied using information provided by the active context. This section describes how to produce an active context.
The active context contains the active term definitions which specify how properties and values have to be interpreted as well as the current base IRI, the vocabulary mapping and the default language. Each term definition consists of an IRI mapping, a boolean flag reverse property, an optional type mapping or language mapping, and an optional container mapping. A term definition can not only be used to map a term to an IRI, but also to map a term to a keyword, in which case it is referred to as a keyword alias.
When processing, the active context is initialized without any term definitions, vocabulary mapping, or default language. If a local context is encountered during processing, a new active context is created by cloning the existing active context. Then the information from the local context is merged into the new active context. Given that local contexts may contain references to remote contexts, this includes their retrieval.
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 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 |
# File 'lib/json/ld/context.rb', line 536 def parse(local_context, remote_contexts: [], protected: false, override_protected: false, propagate: true, validate_scoped: true) result = self.dup result.provided_context = local_context if self.empty? # Early check for @propagate, which can only appear in a local context propagate = local_context.is_a?(Hash) ? local_context.fetch('@propagate', propagate) : propagate result.previous_context ||= result.dup unless propagate local_context = as_array(local_context) local_context.each do |context| case context when nil # 3.1 If the `override_protected` is false, and the active context contains protected terms, an error is raised. if override_protected || result.term_definitions.values.none?(&:protected?) null_context = Context.new(**) null_context.previous_context = result unless propagate result = null_context else raise JSON::LD::JsonLdError::InvalidContextNullification, "Attempt to clear a context with protected terms" end when Context #log_debug("parse") {"context: #{context.inspect}"} result = context.dup when IO, StringIO #log_debug("parse") {"io: #{context}"} # Load context document, if it is an open file begin ctx = JSON.load(context) raise JSON::LD::JsonLdError::InvalidRemoteContext, "Context missing @context key" if @options[:validate] && ctx['@context'].nil? result = result.dup.parse(ctx["@context"] ? ctx["@context"].dup : {}) result.provided_context = ctx["@context"] if [context] == local_context result rescue JSON::ParserError => e #log_debug("parse") {"Failed to parse @context from remote document at #{context}: #{e.message}"} raise JSON::LD::JsonLdError::InvalidRemoteContext, "Failed to parse remote context at #{context}: #{e.}" if @options[:validate] self.dup end when String, RDF::URI #log_debug("parse") {"remote: #{context}, base: #{result.context_base || result.base}"} # 3.2.1) Set context to the result of resolving value against the base IRI which is established as specified in section 5.1 Establishing a Base URI of [RFC3986]. Only the basic algorithm in section 5.2 of [RFC3986] is used; neither Syntax-Based Normalization nor Scheme-Based Normalization are performed. Characters additionally allowed in IRI references are treated in the same way that unreserved characters are treated in URI references, per section 6.5 of [RFC3987]. context = RDF::URI(result.context_base || [:base]).join(context) context_canon = context.canonicalize context_canon.scheme == 'http' if context_canon.scheme == 'https' # If validating a scoped context which has already been loaded, skip to the next one next if !validate_scoped && remote_contexts.include?(context.to_s) remote_contexts << context.to_s raise JsonLdError::ContextOverflow, "#{context}" if remote_contexts.length >= MAX_CONTEXTS_LOADED context_no_base = result.dup context_no_base.base = nil context_no_base.context_base = context.to_s if PRELOADED[context_canon.to_s] # If we have a cached context, merge it into the current context (result) and use as the new context #log_debug("parse") {"=> cached_context: #{context_canon.to_s.inspect}"} # If this is a Proc, then replace the entry with the result of running the Proc if PRELOADED[context_canon.to_s].respond_to?(:call) #log_debug("parse") {"=> (call)"} PRELOADED[context_canon.to_s] = PRELOADED[context_canon.to_s].call end context = context_no_base.merge!(PRELOADED[context_canon.to_s]) else # Load context document, if it is a string begin context_opts = @options.merge( profile: 'http://www.w3.org/ns/json-ld#context', requestProfile: 'http://www.w3.org/ns/json-ld#context', base: nil) #context_opts.delete(:headers) JSON::LD::API.loadRemoteDocument(context.to_s, **context_opts) do |remote_doc| # 3.2.5) Dereference context. If the dereferenced document has no top-level JSON object with an @context member, an invalid remote context has been detected and processing is aborted; otherwise, set context to the value of that member. raise JsonLdError::InvalidRemoteContext, "#{context}" unless remote_doc.document.is_a?(Hash) && remote_doc.document.has_key?('@context') context = remote_doc.document['@context'] end rescue JsonLdError::LoadingDocumentFailed => e #log_debug("parse") {"Failed to retrieve @context from remote document at #{context_no_base.context_base.inspect}: #{e.message}"} raise JsonLdError::LoadingRemoteContextFailed, "#{context_no_base.context_base}: #{e.}", e.backtrace rescue JsonLdError raise rescue StandardError => e #log_debug("parse") {"Failed to retrieve @context from remote document at #{context_no_base.context_base.inspect}: #{e.message}"} raise JsonLdError::LoadingRemoteContextFailed, "#{context_no_base.context_base}: #{e.}", e.backtrace end # 3.2.6) Set context to the result of recursively calling this algorithm, passing context no base for active context, context for local context, and remote contexts. context = context_no_base.parse(context, remote_contexts: remote_contexts.dup, protected: protected, override_protected: override_protected, propagate: propagate, validate_scoped: validate_scoped) PRELOADED[context_canon.to_s] = context.dup context.provided_context = result.provided_context end context.base ||= result.base result = context #log_debug("parse") {"=> provided_context: #{context.inspect}"} when Hash context = context.dup # keep from modifying a hash passed as a param # This counts on hash elements being processed in order { '@version' => :processingMode=, '@import' => nil, '@base' => :base=, '@direction' => :default_direction=, '@language' => :default_language=, '@propagate' => :propagate=, '@vocab' => :vocab=, }.each do |key, setter| next unless context.has_key?(key) if key == '@import' # Retrieve remote context and merge the remaining context object into the result. raise JsonLdError::InvalidContextEntry, "@import may only be used in 1.1 mode}" if result.processingMode("json-ld-1.0") raise JsonLdError::InvalidImportValue, "@import must be a string: #{context['@import'].inspect}" unless context['@import'].is_a?(String) source = RDF::URI(result.context_base || result.base).join(context['@import']) begin context_opts = @options.merge( profile: 'http://www.w3.org/ns/json-ld#context', requestProfile: 'http://www.w3.org/ns/json-ld#context', base: nil) context_opts.delete(:headers) JSON::LD::API.loadRemoteDocument(source, **context_opts) do |remote_doc| # Dereference source. If the dereferenced document has no top-level JSON object with an @context member, an invalid remote context has been detected and processing is aborted; otherwise, set context to the value of that member. raise JsonLdError::InvalidRemoteContext, "#{source}" unless remote_doc.document.is_a?(Hash) && remote_doc.document.has_key?('@context') import_context = remote_doc.document['@context'] raise JsonLdError::InvalidRemoteContext, "#{import_context.to_json} must be an object" unless import_context.is_a?(Hash) raise JsonLdError::InvalidContextEntry, "#{import_context.to_json} must not include @import entry" if import_context.has_key?('@import') context.delete(key) context = import_context.merge(context) end rescue JsonLdError::LoadingDocumentFailed => e raise JsonLdError::LoadingRemoteContextFailed, "#{source}: #{e.}", e.backtrace rescue JsonLdError raise rescue StandardError => e raise JsonLdError::LoadingRemoteContextFailed, "#{source}: #{e.}", e.backtrace end else result.send(setter, context[key], remote_contexts: remote_contexts, protected: context.fetch('@protected', protected)) end context.delete(key) end defined = {} # For each key-value pair in context invoke the Create Term Definition subalgorithm, passing result for active context, context for local context, key, and defined context.each_key do |key| # ... where key is not @base, @vocab, @language, or @version result.create_term_definition(context, key, defined, override_protected: override_protected, protected: context.fetch('@protected', protected), remote_contexts: remote_contexts.dup, validate_scoped: validate_scoped ) unless NON_TERMDEF_KEYS.include?(key) end else # 3.3) If context is not a JSON object, an invalid local context error has been detected and processing is aborted. raise JsonLdError::InvalidLocalContext, "must be a URL, JSON object or array of same: #{context.inspect}" end end result end |
#processingMode(expected = nil) ⇒ String
Retrieve, or check processing mode.
-
With no arguments, retrieves the current set processingMode.
-
With an argument, verifies that the processingMode is at least that provided, either as an integer, or a string of the form “json-ld-1.x”
-
If expecting 1.1, and not set, it has the side-effect of setting mode to json-ld-1.1.
444 445 446 447 448 449 450 451 452 453 454 455 456 |
# File 'lib/json/ld/context.rb', line 444 def processingMode(expected = nil) case expected when 1.0, 'json-ld-1.0' @processingMode == 'json-ld-1.0' when 1.1, 'json-ld-1.1' @processingMode ||= 'json-ld-1.1' @processingMode == 'json-ld-1.1' when nil @processingMode else false end end |
#processingMode=(value = nil, **options) ⇒ String
Set processing mode.
-
With an argument, verifies that the processingMode is at least that provided, either as an integer, or a string of the form “json-ld-1.x”
If contex has a @version member, it’s value MUST be 1.1, otherwise an “invalid @version value” has been detected, and processing is aborted. If processingMode has been set, and it is not “json-ld-1.1”, a “processing mode conflict” has been detecting, and processing is aborted.
469 470 471 472 473 474 475 476 477 478 479 480 |
# File 'lib/json/ld/context.rb', line 469 def processingMode=(value = nil, **) value = "json-ld-1.1" if value == 1.1 case value when "json-ld-1.0", "json-ld-1.1" if @processingMode && @processingMode != value raise JsonLdError::ProcessingModeConflict, "#{value} not compatible with #{@processingMode}" end @processingMode = value else raise JsonLdError::InvalidVersionValue, value.inspect end end |
#propagate=(value, **options) ⇒ Object
Set propagation @note: by the time this is called, the work has already been done.
508 509 510 511 512 |
# File 'lib/json/ld/context.rb', line 508 def propagate=(value, **) raise JsonLdError::InvalidContextEntry, "@propagate may only be set in 1.1 mode" if processingMode("json-ld-1.0") raise JsonLdError::InvalidPropagateValue, "@propagate must be boolean valued: #{value.inspect}" unless value.is_a?(TrueClass) || value.is_a?(FalseClass) value end |
#reverse?(term) ⇒ Boolean
Is this a reverse term
1289 1290 1291 1292 |
# File 'lib/json/ld/context.rb', line 1289 def reverse?(term) term = find_definition(term) term && term.reverse_property end |
#reverse_term(term) ⇒ Term
Given a term or IRI, find a reverse term definition matching that term. If the term is already reversed, find a non-reversed version.
1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 |
# File 'lib/json/ld/context.rb', line 1299 def reverse_term(term) # Direct lookup of term term = term_definitions[term.to_s] if term_definitions.has_key?(term.to_s) && !term.is_a?(TermDefinition) # Lookup term, assuming term is an IRI unless term.is_a?(TermDefinition) td = term_definitions.values.detect {|t| t.id == term.to_s} # Otherwise create a temporary term definition term = td || TermDefinition.new(term.to_s, id: (term, vocab:true)) end # Now, return a term, which reverses this term term_definitions.values.detect {|t| t.id == term.id && t.reverse_property != term.reverse_property} end |
#serialize(**options) ⇒ Hash
Generate @context
If a context was supplied in global options, use that, otherwise, generate one from this representation.
1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 |
# File 'lib/json/ld/context.rb', line 1061 def serialize(**) # FIXME: not setting provided_context now use_context = case provided_context when String, RDF::URI #log_debug "serlialize: reuse context: #{provided_context.inspect}" provided_context.to_s when Hash, Array #log_debug "serlialize: reuse context: #{provided_context.inspect}" provided_context else #log_debug("serlialize: generate context") #log_debug("") {"=> context: #{inspect}"} ctx = {} ctx['@base'] = base.to_s if base && base != doc_base ctx['@direction'] = default_direction.to_s if default_direction ctx['@language'] = default_language.to_s if default_language ctx['@vocab'] = vocab.to_s if vocab # Term Definitions term_definitions.keys.each do |term| defn = term_definitions[term].to_context_definition(self) ctx[term] = defn if defn end #log_debug("") {"start_doc: context=#{ctx.inspect}"} ctx end # Return hash with @context, or empty r = {} r['@context'] = use_context unless use_context.nil? || use_context.empty? r end |
#set_mapping(term, value) ⇒ TermDefinition
Set term mapping
1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 |
# File 'lib/json/ld/context.rb', line 1177 def set_mapping(term, value) #log_debug("") {"map #{term.inspect} to #{value.inspect}"} term = term.to_s term_definitions[term] = TermDefinition.new(term, id: value, simple: true, prefix: (value.to_s.end_with?(*PREFIX_URI_ENDINGS))) term_definitions[term].simple = true term_sym = term.empty? ? "" : term.to_sym iri_to_term.delete(term_definitions[term].id.to_s) if term_definitions[term].id.is_a?(String) @options[:prefixes][term_sym] = value if @options.has_key?(:prefixes) iri_to_term[value.to_s] = term term_definitions[term] end |
#to_rb(*aliases) ⇒ String
Turn this into a source for a new instantiation
1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 |
# File 'lib/json/ld/context.rb', line 1795 def to_rb(*aliases) canon_base = RDF::URI(context_base).canonicalize defn = [] defn << "base: #{self.base.to_s.inspect}" if self.base defn << "language: #{self.default_language.inspect}" if self.default_language defn << "vocab: #{self.vocab.to_s.inspect}" if self.vocab defn << "processingMode: #{self.processingMode.inspect}" if self.processingMode term_defs = term_definitions.map do |term, td| " " + term.inspect + " => " + td.to_rb end.sort defn << "term_definitions: {\n#{term_defs.join(",\n") }\n }" unless term_defs.empty? %(# -*- encoding: utf-8 -*- # frozen_string_literal: true # This file generated automatically from #{context_base} require 'json/ld' class JSON::LD::Context ).gsub(/^ /, '') + %[ add_preloaded("#{canon_base}") do\n new(] + defn.join(", ") + ")\n end\n" + aliases.map {|a| %[ alias_preloaded("#{a}", "#{canon_base}")\n]}.join("") + "end\n" end |