Class: RDF::Tabular::Metadata
- Inherits:
-
Object
- Object
- RDF::Tabular::Metadata
- Includes:
- Utils
- Defined in:
- lib/rdf/tabular/metadata.rb
Direct Known Subclasses
Defined Under Namespace
Classes: DebugContext
Constant Summary collapse
- INHERITED_PROPERTIES =
Inheritect properties, valid for all types
{ null: :atomic, lang: :atomic, textDirection: :atomic, separator: :atomic, default: :atomic, ordered: :atomic, datatype: :atomic, aboutUrl: :uri_template, propertyUrl: :uri_template, valueUrl: :uri_template, }.freeze
- DATATYPES =
Valid datatypes
{ anyAtomicType: RDF::XSD.anySimpleType, anyURI: RDF::XSD.anyURI, base64Binary: RDF::XSD.basee65Binary, boolean: RDF::XSD.boolean, byte: RDF::XSD.byte, date: RDF::XSD.date, dateTime: RDF::XSD.dateTime, dateTimeDuration: RDF::XSD.dateTimeDuration, dateTimeStamp: RDF::XSD.dateTimeStamp, decimal: RDF::XSD.decimal, double: RDF::XSD.double, float: RDF::XSD.float, ENTITY: RDF::XSD.ENTITY, gDay: RDF::XSD.gDay, gMonth: RDF::XSD.gMonth, gMonthDay: RDF::XSD.gMonthDay, gYear: RDF::XSD.gYear, gYearMonth: RDF::XSD.gYearMonth, hexBinary: RDF::XSD.hexBinary, int: RDF::XSD.int, integer: RDF::XSD.integer, language: RDF::XSD.language, long: RDF::XSD.long, Name: RDF::XSD.Name, NCName: RDF::XSD.NCName, negativeInteger: RDF::XSD.negativeInteger, nonNegativeInteger: RDF::XSD.nonNegativeInteger, nonPositiveInteger: RDF::XSD.nonPositiveInteger, normalizedString: RDF::XSD.normalizedString, NOTATION: RDF::XSD.NOTATION, positiveInteger: RDF::XSD.positiveInteger, QName: RDF::XSD.Qname, short: RDF::XSD.short, string: RDF::XSD.string, time: RDF::XSD.time, token: RDF::XSD.token, unsignedByte: RDF::XSD.unsignedByte, unsignedInt: RDF::XSD.unsignedInt, unsignedLong: RDF::XSD.unsignedLong, unsignedShort: RDF::XSD.unsignedShort, yearMonthDuration: RDF::XSD.yearMonthDuration, any: RDF::XSD.anySimpleType, binary: RDF::XSD.base64Binary, datetime: RDF::XSD.dateTime, html: RDF.HTML, json: RDF::Tabular::CSVW.JSON, number: RDF::XSD.double, xml: RDF.XMLLiteral, }
- NAME_SYNTAX =
A name is restricted according to the following RegExp.
%r(\A(?:_col|[a-zA-Z0-9]|%\h\h)([a-zA-Z0-9\._]|%\h\h)*\z)- LOCAL_CONTEXT =
Local version of the context
::JSON::LD::Context.new.parse(File.("../../../../etc/csvw.jsonld", __FILE__))
Instance Attribute Summary collapse
-
#filenames ⇒ Array<RDF::URI>
readonly
Filename(s) (URI) of opened metadata, if any May be plural when merged.
-
#id ⇒ RDF::URI
readonly
ID of this Metadata.
-
#object ⇒ Object
Hash representation.
-
#parent ⇒ Metadata
readonly
Parent of this Metadata (TableGroup for Table, …).
-
#url ⇒ RDF::URI
readonly
URL of related resource.
Class Method Summary collapse
-
.for_input(input, options = {}) ⇒ Metadata
Return metadata for a file, based on user-specified and path-relative locations from an input file.
- .new(input, options = {}) ⇒ Object
-
.open(path, options = {}) ⇒ Object
Attempt to retrieve the file at the specified path.
Instance Method Summary collapse
- #==(other) ⇒ Object
-
#[](key) ⇒ Object
Proxy to @object.
- #[]=(key, value) ⇒ Object
-
#base ⇒ RDF::URI
Base URL of metadata.
-
#common_properties(subject, property, value, &block) ⇒ Object
Return JSON-friendly or yield RDF for common properties.
-
#context ⇒ JSON::LD::Context
Context used for this metadata.
-
#dialect ⇒ Dialect
Treat ‘dialect` similar to an inherited property, but merge together values from Table and TableGroup.
-
#dialect=(value) ⇒ Dialect
Set new dialect.
- #each(&block) ⇒ Object
-
#each_row(input) {|Row| ... } ⇒ Object
Yield each data row from the input file.
-
#errors ⇒ Array<String>
Validation errors.
-
#has_annotations? ⇒ Boolean
Does the Metadata have any common properties?.
-
#initialize(input, options = {}) ⇒ Metadata
constructor
Create Metadata from IO, Hash or String.
- #inspect ⇒ Object
-
#merge(*metadata) ⇒ Metadata
Merge metadata into this a copy of this metadata.
-
#merge!(metadata) ⇒ Object
Merge metadata into self.
-
#normalize! ⇒ self
Normalize object.
-
#normalize_datatype(value) ⇒ Hash{Symbol => String}
Normalize datatype to Object/Hash representation.
-
#normalize_jsonld(property, value) ⇒ String, ...
Normalize JSON-LD.
- #to_json(args = nil) ⇒ Object
-
#type ⇒ :TableGroup, ...
Type of this Metadata.
-
#valid? ⇒ Boolean
Do we have valid metadata?.
-
#valid_inherited_property?(key, value) { ... } ⇒ Boolean
Determine if an inherited property is valid.
-
#valid_natural_language_property?(key, value) { ... } ⇒ Boolean
Determine if a natural language property is valid.
-
#validate! ⇒ self
Validate metadata, raising an error containing all errors detected during validation.
Methods included from Utils
Constructor Details
#initialize(input, options = {}) ⇒ Metadata
Create Metadata from IO, Hash or String
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 319 320 321 322 323 324 325 326 327 328 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 |
# File 'lib/rdf/tabular/metadata.rb', line 265 def initialize(input, = {}) @options = .dup # Get context from input # Optimize by using built-in version of context, and just extract @base, @lang @context = case input['@context'] when Array then LOCAL_CONTEXT.parse(input['@context'].detect {|e| e.is_a?(Hash)} || {}) when Hash then LOCAL_CONTEXT.parse(input['@context']) when nil then nil else LOCAL_CONTEXT end reason = @options.delete(:reason) @options[:base] ||= @context.base if @context @options[:base] ||= input.base_uri if input.respond_to?(:base_uri) @options[:base] ||= input.filename if input.respond_to?(:filename) @options[:base] = RDF::URI(@options[:base]) @context.base = @options[:base] if @context @options[:depth] ||= 0 @filenames = Array(@options[:filenames]).map {|fn| RDF::URI(fn)} if @options[:filenames] @properties = self.class.const_get(:PROPERTIES) @required = self.class.const_get(:REQUIRED) @object = {} # Parent of this Metadata, if any @parent = @options[:parent] depth do # Input was parsed in .new # Metadata is object with symbolic keys input.each do |key, value| key = key.to_sym case key when :columns # An array of template specifications that provide mechanisms to transform the tabular data into other formats object[key] = if value.is_a?(Array) && value.all? {|v| v.is_a?(Hash)} number = 0 value.map do |v| number += 1 Column.new(v, @options.merge(table: (parent if parent.is_a?(Table)), parent: self, context: nil, number: number)) end else # Invalid, but preserve value value end when :datatype # If in object form, normalize keys to symbols object[key] = case value when Hash value.inject({}) {|memo, (k,v)| memo[k.to_sym] = v; memo} else value end when :dialect # If provided, dialect provides hints to processors about how to parse the referenced file to create a tabular data model. object[key] = case value when String then Dialect.open(base.join(value), @options.merge(parent: self, context: nil)) when Hash then Dialect.new(value, @options.merge(parent: self, context: nil)) else # Invalid, but preserve value value end @type ||= :Table when :resources # An array of table descriptions for the tables in the group. object[key] = if value.is_a?(Array) && value.all? {|v| v.is_a?(Hash)} value.map {|v| Table.new(v, @options.merge(parent: self, context: nil))} else # Invalid, but preserve value value end when :tableSchema # An object property that provides a schema description as described in section 3.8 Schemas, for all the tables in the group. This may be provided as an embedded object within the JSON metadata or as a URL reference to a separate JSON schema document # SPEC SUGGESTION: when loading a remote schema, assign @id from it's location if not already set object[key] = case value when String link = base.join(value).to_s s = Schema.open(link, @options.merge(parent: self, context: nil)) s[:@id] ||= link s when Hash then Schema.new(value, @options.merge(parent: self, context: nil)) else # Invalid, but preserve value value end when :transformations # An array of template specifications that provide mechanisms to transform the tabular data into other formats object[key] = if value.is_a?(Array) && value.all? {|v| v.is_a?(Hash)} value.map {|v| Transformation.new(v, @options.merge(parent: self, context: nil))} else # Invalid, but preserve value value end when :url # URL of CSV relative to metadata object[:url] = value @url = base.join(value) @context.base = @url if @context # Use as base for expanding IRIs when :@id # metadata identifier object[:@id] = value @id = base.join(value) else if @properties.has_key?(key) self.send("#{key}=".to_sym, value) else object[key] = value end end end end # Set type from @type, if present and not otherwise defined @type ||= object[:@type].to_sym if object[:@type] if reason debug("md#initialize") {reason} debug("md#initialize") {"filenames: #{filenames}"} debug("md#initialize") {"#{inspect}, parent: #{!@parent.nil?}, context: #{!@context.nil?}"} unless is_a?(Dialect) end end |
Instance Attribute Details
#filenames ⇒ Array<RDF::URI> (readonly)
Filename(s) (URI) of opened metadata, if any May be plural when merged
115 116 117 |
# File 'lib/rdf/tabular/metadata.rb', line 115 def filenames @filenames end |
#id ⇒ RDF::URI (readonly)
ID of this Metadata
102 103 104 |
# File 'lib/rdf/tabular/metadata.rb', line 102 def id @id end |
#object ⇒ Object
Hash representation
23 24 25 |
# File 'lib/rdf/tabular/metadata.rb', line 23 def object @object end |
#parent ⇒ Metadata (readonly)
Parent of this Metadata (TableGroup for Table, …)
110 111 112 |
# File 'lib/rdf/tabular/metadata.rb', line 110 def parent @parent end |
#url ⇒ RDF::URI (readonly)
URL of related resource
106 107 108 |
# File 'lib/rdf/tabular/metadata.rb', line 106 def url @url end |
Class Method Details
.for_input(input, options = {}) ⇒ Metadata
Return metadata for a file, based on user-specified and path-relative locations from an input file
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 |
# File 'lib/rdf/tabular/metadata.rb', line 143 def self.for_input(input, = {}) base = [:base] # Use user metadata = case [:metadata] when Metadata then [:metadata] when Hash Metadata.new([:metadata], .merge(reason: "load user metadata: #{[:metadata].inspect}")) when String, RDF::URI Metadata.open([:metadata], .merge(filenames: [:metadata], reason: "load user metadata: #{[:metadata].inspect}")) end = nil # If user_metadata does not describe input, get the first found from linked-, file-, and directory-specific metadata unless .is_a?(Table) || .is_a?(TableGroup) && .for_table(base) # load link metadata, if available locs = [] if input.respond_to?(:links) && link = input.links.find_link(%w(rel describedby)) locs << RDF::URI(base).join(link.href) end if base locs += [RDF::URI("#{base}-metadata.json"), RDF::URI(base).join("metadata.json")] end locs.each do |loc| ||= begin Metadata.open(loc, .merge(filenames: loc, reason: "load found metadata: #{loc}")) rescue debug("for_input", ) {"failed to load found metadata #{loc}: #{$!}"} nil end end end # Return either the merge or user- and found-metadata, any of these, or an empty TableGroup = case when && then .merge() when then when then else TableGroup.new({resources: [{url: base}]}, ) end # Make TableGroup, if not already .is_a?(TableGroup) ? : .merge(TableGroup.new({})) end |
.new(input, options = {}) ⇒ Object
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 |
# File 'lib/rdf/tabular/metadata.rb', line 194 def self.new(input, = {}) # Triveal case return input if input.is_a?(Metadata) object = case input when Hash then input when IO, StringIO then ::JSON.parse(input.read) else ::JSON.parse(input.to_s) end unless [:parent] # Add context, if not set (which it should be) object['@context'] ||= .delete(:@context) || [:context] || 'http://www.w3.org/ns/csvw' end klass = case when !self.equal?(RDF::Tabular::Metadata) self # subclasses can be directly constructed without type dispatch else type = if [:type] type = [:type].to_sym raise Error, "If provided, type must be one of :TableGroup, :Table, :Transformation, :Schema, :Column, :Dialect]" unless [:TableGroup, :Table, :Transformation, :Schema, :Column, :Dialect].include?(type) type end # Figure out type by @type type ||= object['@type'] # Figure out type by site object_keys = object.keys.map(&:to_s) type ||= case when %w(resources).any? {|k| object_keys.include?(k)} then :TableGroup when %w(dialect tableSchema transformations).any? {|k| object_keys.include?(k)} then :Table when %w(targetFormat scriptFormat source).any? {|k| object_keys.include?(k)} then :Transformation when %w(columns primaryKey foreignKeys urlTemplate).any? {|k| object_keys.include?(k)} then :Schema when %w(name required).any? {|k| object_keys.include?(k)} then :Column when %w(commentPrefix delimiter doubleQuote encoding header headerColumnCount headerRowCount).any? {|k| object_keys.include?(k)} then :Dialect when %w(lineTerminator quoteChar skipBlankRows skipColumns skipInitialSpace skipRows trim).any? {|k| object_keys.include?(k)} then :Dialect end case type.to_s.to_sym when :TableGroup then RDF::Tabular::TableGroup when :Table then RDF::Tabular::Table when :Transformation then RDF::Tabular::Transformation when :Schema then RDF::Tabular::Schema when :Column then RDF::Tabular::Column when :Dialect then RDF::Tabular::Dialect else raise Error, "Unkown metadata type: #{type.inspect}" end end md = klass.allocate md.send(:initialize, object, ) md end |
.open(path, options = {}) ⇒ Object
Attempt to retrieve the file at the specified path. If it is valid metadata, create a new Metadata object from it, otherwise, an empty Metadata object
123 124 125 126 127 128 129 130 131 132 133 |
# File 'lib/rdf/tabular/metadata.rb', line 123 def self.open(path, = {}) = .merge( headers: { 'Accept' => 'application/ld+json, application/json' } ) path = "file:" + path unless path =~ /^\w+:/ RDF::Util::File.open_file(path, ) do |file| self.new(file, .merge(base: path, filenames: path)) end end |
Instance Method Details
#==(other) ⇒ Object
1087 1088 1089 |
# File 'lib/rdf/tabular/metadata.rb', line 1087 def ==(other) object == (other.is_a?(Hash) ? other : other.object) end |
#[](key) ⇒ Object
Proxy to @object
1084 |
# File 'lib/rdf/tabular/metadata.rb', line 1084 def [](key); object[key]; end |
#[]=(key, value) ⇒ Object
1085 |
# File 'lib/rdf/tabular/metadata.rb', line 1085 def []=(key, value); object[key] = value; end |
#base ⇒ RDF::URI
Base URL of metadata
446 |
# File 'lib/rdf/tabular/metadata.rb', line 446 def base; @options[:base]; end |
#common_properties(subject, property, value) {|property, statement| ... } ⇒ Object #common_properties(subject, property, value) ⇒ String, ...
Return JSON-friendly or yield RDF for common properties
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 |
# File 'lib/rdf/tabular/metadata.rb', line 813 def common_properties(subject, property, value, &block) if block_given? property = context.(property.to_s, vocab: true) unless property.is_a?(RDF::URI) case value when Array value.each {|v| common_properties(subject, property, v, &block)} when Hash if value['@value'] dt = RDF::URI(context.(value['@type'], vocab: true)) if value['@type'] lit = RDF::Literal(value['@value'], language: value['@language'], datatype: dt) block.call(RDF::Statement.new(subject, property, lit)) else # value MUST be a node object, establish a new subject from `@id` s2 = value.has_key?('@id') ? context.(value['@id']) : RDF::Node.new # Generate a triple block.call(RDF::Statement.new(subject, property, s2)) # Generate types Array(value['@type']).each do |t| block.call(RDF::Statement.new(s2, RDF.type, context.(t, vocab: true))) end # Generate triples for all other properties value.each do |prop, val| next if prop.to_s.start_with?('@') common_properties(s2, prop, val, &block) end end else # Value is a primitive JSON value lit = RDF::Literal(value) block.call(RDF::Statement.new(subject, property, RDF::Literal(value))) end else case value when Array value.map {|v| common_properties(subject, property, v)} when Hash if value['@value'] value['@value'] elsif value.keys == %w(@id) && value['@id'] value['@id'] else nv = {} value.each do |k, v| case k.to_s when '@id' then nv[k.to_s] = context.(v['@id']).to_s when '@type' then nv[k.to_s] = v else nv[k.to_s] = common_properties(nil, k, v) end end nv end else value end end end |
#context ⇒ JSON::LD::Context
Context used for this metadata. Use parent’s if not defined on self.
399 400 401 |
# File 'lib/rdf/tabular/metadata.rb', line 399 def context @context || (parent.context if parent) end |
#dialect ⇒ Dialect
Treat ‘dialect` similar to an inherited property, but merge together values from Table and TableGroup
405 406 407 408 409 410 411 412 413 414 415 416 |
# File 'lib/rdf/tabular/metadata.rb', line 405 def dialect @dialect ||= case when object[:dialect] then object[:dialect] when parent then parent.dialect when is_a?(Table) || is_a?(TableGroup) d = Dialect.new({}, @options.merge(parent: self, context: nil)) self.dialect = d unless self.parent d else raise Error, "Can't access dialect from #{self.class} without a parent" end end |
#dialect=(value) ⇒ Dialect
Set new dialect
420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 |
# File 'lib/rdf/tabular/metadata.rb', line 420 def dialect=(value) # Clear cached dialect information from children object.values.each do |v| case v when Metadata then v.object.delete(:dialect) when Array then v.each {|vv| vv.object.delete(:dialect) if vv.is_a?(Metadata)} end end if value.is_a?(Hash) @dialect = object[:dialect] = Dialect.new(value) elsif value # Remember invalid dialect for validation purposes object[:dialect] = value else object.delete(:dialect) @dialect = nil end end |
#each(&block) ⇒ Object
1086 |
# File 'lib/rdf/tabular/metadata.rb', line 1086 def each(&block); object.each(&block); end |
#each_row(input) {|Row| ... } ⇒ Object
Yield each data row from the input file
774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 |
# File 'lib/rdf/tabular/metadata.rb', line 774 def each_row(input) csv = ::CSV.new(input, ) # Skip skipRows and headerRowCount number, skipped = 0, (dialect.skipRows.to_i + dialect.headerRowCount) (1..skipped).each {csv.shift} csv.each do |data| # Check for embedded comments if dialect.commentPrefix && data.first.to_s.start_with?(dialect.commentPrefix) v = data.join(' ')[1..-1].strip unless v.empty? (self["rdfs:comment"] ||= []) << v yield RDF::Statement.new(nil, RDF::RDFS.comment, RDF::Literal(v)) end skipped += 1 next elsif dialect.skipBlankRows && data.join("").strip.empty? skipped += 1 next end number += 1 yield(Row.new(data, self, number, number + skipped)) end end |
#errors ⇒ Array<String>
Validation errors
460 461 462 463 464 |
# File 'lib/rdf/tabular/metadata.rb', line 460 def errors validate! && [] rescue Error => e e..split("\n") end |
#has_annotations? ⇒ Boolean
Does the Metadata have any common properties?
875 876 877 |
# File 'lib/rdf/tabular/metadata.rb', line 875 def has_annotations? object.keys.any? {|k| k.to_s.include?(':')} end |
#inspect ⇒ Object
1079 1080 1081 |
# File 'lib/rdf/tabular/metadata.rb', line 1079 def inspect self.class.name + object.inspect end |
#merge(*metadata) ⇒ Metadata
Merge metadata into this a copy of this metadata
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 |
# File 'lib/rdf/tabular/metadata.rb', line 882 def merge(*) return self if .empty? # If the top-level object of any of the metadata files are table descriptions, these are treated as if they were table group descriptions containing a single table description (ie having a single resource property whose value is the same as the original table description). this = case self when TableGroup then self.dup when Table if self.is_a?(Table) && self.parent self.parent else content = {"@type" => "TableGroup", "resources" => [self]} content['@context'] = object.delete(:@context) if object[:@context] ctx = @context self.remove_instance_variable(:@context) if self.instance_variables.include?(:@context) tg = TableGroup.new(content, filenames: @filenames, base: base) @parent = tg # Link from parent tg end else self.dup end # Merge all passed metadata into this merged = .reduce(this) do |memo, md| md = case md when TableGroup then md when Table if md.parent md.parent else content = {"@type" => "TableGroup", "resources" => [md]} ctx = md.context content['@context'] = md.object.delete(:@context) if md.object[:@context] md.remove_instance_variable(:@context) if md.instance_variables.include?(:@context) tg = TableGroup.new(content, filenames: md.filenames, base: md.base) md.instance_variable_set(:@parent, tg) # Link from parent tg end else md end raise "Can't merge #{memo.class} with #{md.class}" unless memo.class == md.class memo.merge!(md) end # Set @context of merged merged[:@context] = 'http://www.w3.org/ns/csvw' merged end |
#merge!(metadata) ⇒ Object
Merge metadata into self
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 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 |
# File 'lib/rdf/tabular/metadata.rb', line 933 def merge!() raise "Merging non-equivalent metadata types: #{self.class} vs #{.class}" unless self.class == .class depth do # Merge filenames if @filenames || .filenames @filenames = (Array(@filenames) | Array(.filenames)).uniq end # Normalize A (this) and B (metadata) values into normal form self.normalize! = .dup.normalize! @dialect = nil # So that it is re-built when needed # Merge each property from metadata into self .each do |key, value| case @properties[key] when :array # If the property is an array property, the way in which values are merged depends on the property; see the relevant property for this definition. object[key] = case object[key] when nil then [] when Hash then [object[key]] # Shouldn't happen if well formed else object[key] end value = [value] if value.is_a?(Hash) case key when :notes # If the property is notes, the result is an array containing values from A followed by values from B. a = object[key].is_a?(Array) ? object[key] : [object[key]].compact b = value.is_a?(Array) ? value : [value] object[key] = a + b when :resources # When an array of table descriptions B is imported into an original array of table descriptions A, each table description within B is combined into the original array A by: value.each do |tb| if ta = object[key].detect {|e| e.url == tb.url} # if there is a table description with the same url in A, the table description from B is imported into the matching table description in A debug("merge!: resources") {"TA: #{ta.inspect}, TB: #{tb.inspect}"} ta.merge!(tb) else # otherwise, the table description from B is appended to the array of table descriptions A tb = tb.dup tb.instance_variable_set(:@parent, self) debug("merge!: resources") {"add TB: #{tb.inspect}"} object[key] << tb end end when :transformations # SPEC CONFUSION: differing transformations with same @id? # When an array of template specifications B is imported into an original array of template specifications A, each template specification within B is combined into the original array A by: value.each do |t| if ta = object[key].detect {|e| e.targetFormat == t.targetFormat && e.scriptFormat == t.scriptFormat} # if there is a template specification with the same targetFormat and scriptFormat in A, the template specification from B is imported into the matching template specification in A ta.merge!(t) else # otherwise, the template specification from B is appended to the array of template specifications A t = t.dup t.instance_variable_set(:@parent, self) if self object[key] << t end end when :columns # When an array of column descriptions B is imported into an original array of column descriptions A, each column description within B is combined into the original array A by: Array(value).each_with_index do |cb, index| ca = object[key][index] || {} va = ([ca[:name]] + (ca[:title] || {}).values.flatten).compact.map(&:downcase) vb = ([cb[:name]] + (cb[:title] || {}).values.flatten).compact.map(&:downcase) if !(va & vb).empty? debug("merge!: columns") {"index: #{index}, va: #{va}, vb: #{vb}"} # If there's a non-empty case-insensitive intersection between the name and title values for the column description at the same index within A and B, the column description from B is imported into the matching column description in A ca.merge!(cb) elsif ca.nil? && cb.virtual debug("merge!: columns") {"index: #{index}, virtual"} # otherwise, if at a given index there is no column description within A, but there is a column description within B. cb = cb.dup cb.instance_variable_set(:@parent, self) if self object[key][index] = cb else debug("merge!: columns") {"index: #{index}, ignore"} raise Error, "Columns at same index don't match: #{ca.to_json} vs. #{cb.to_json}" end end # The number of non-virtual columns in A and B MUST be the same nA = object[key].reject(&:virtual).length nB = Array(value).reject(&:virtual).length raise Error, "Columns must have the same number of non-virtual columns" unless nA == nB || nB == 0 when :foreignKeys # When an array of foreign key definitions B is imported into an original array of foreign key definitions A, each foreign key definition within B which does not appear within A is appended to the original array A. # SPEC CONFUSION: If definitions vary only a little, they should probably be merged (e.g. common properties). object[key] = object[key] + ([key] - object[key]) end when :object case key when :notes # If the property accepts arrays, the result is an array of objects or strings: those from A followed by those from B that were not already a value in A. a = object[key] || [] object[key] = (a + value).uniq else # if the property only accepts single objects if object[key].is_a?(String) || value.is_a?(String) # if the value of the property in A is a string or the value from B is a string then the value from A overrides that from B object[key] ||= value elsif object[key].is_a?(Metadata) # otherwise (if both values as objects) the objects are merged as described here object[key].merge!(value) elsif object[key].is_a?(Hash) # otherwise (if both values as objects) the objects are merged as described here object[key].merge!(value) else value = value.dup value.instance_variable_set(:@parent, self) if self object[key] = value end end when :natural_language # If the property is a natural language property, the result is an object whose properties are language codes and where the values of those properties are arrays. The suitable language code for the values is either explicit within the existing value or determined through the default language in the metadata document; if it can't be determined the language code und should be used. The arrays should provide the values from A followed by those from B that were not already a value in A. a = object[key] || {} b = value debug("merge!: natural_language") { "A: #{a.inspect}, B: #{b.inspect}" } b.each do |k, v| a[k] = Array(a[k]) + (Array(b[k]) - Array(a[k])) end # eliminate titles with no language where the same string exists with a language if a.has_key?("und") a["und"] = a["und"].reject do |v| a.any? {|lang, values| lang != 'und' && values.include?(v)} end a.delete("und") if a["und"].empty? end object[key] = a when ->(k) {key == :@id} object[key] ||= value @id ||= .id else # Otherwise, the value from A overrides that from B object[key] ||= value end end end debug("merge!") {self.inspect} self end |
#normalize! ⇒ self
Normalize object
1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 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 |
# File 'lib/rdf/tabular/metadata.rb', line 1096 def normalize! self.each do |key, value| self[key] = case @properties[key] || INHERITED_PROPERTIES[key] when ->(k) {key.to_s.include?(':') || key == :notes} normalize_jsonld(key, value) when ->(k) {key.to_s == '@context'} "http://www.w3.org/ns/csvw" when :link base.join(value).to_s when :array value = [value] unless value.is_a?(Array) value.map do |v| if v.is_a?(Metadata) v.normalize! elsif v.is_a?(Hash) && (ref = v["reference"]).is_a?(Hash) # SPEC SUGGESTION: special case for foreignKeys ref["resource"] = base.join(ref["resource"]).to_s if ref["resource"] ref["schemaReference"] = base.join(ref["schemaReference"]).to_s if ref["schemaReference"] v else v end end when :object case value when Metadata then value.normalize! when String # Load referenced JSON document # (This is done when objects are loaded in this implementation) raise "unexpected String value of property '#{key}': #{value}" else value end when :natural_language value.is_a?(Hash) ? value : {(context.default_language || 'und') => Array(value)} when :atomic case key when :datatype then normalize_datatype(value) else value end else value end end self end |
#normalize_datatype(value) ⇒ Hash{Symbol => String}
Normalize datatype to Object/Hash representation
1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 |
# File 'lib/rdf/tabular/metadata.rb', line 1146 def normalize_datatype(value) # Normalize datatype to array of object form value = {base: value} unless value.is_a?(Hash) # Create a new representation using symbols and transformed values nv = {} value.each do |kk, vv| case kk.to_sym when :base, :decimalChar, :format, :groupChar, :pattern then nv[kk.to_sym] = vv when :length, :minLength, :maxLength, :minimum, :maximum, :minInclusive, :maxInclusive, :minExclusive, :maxExclusive nv[kk.to_sym] = vv.to_i end end nv[:base] ||= 'string' nv end |
#normalize_jsonld(property, value) ⇒ String, ...
Normalize JSON-LD
Also, raise error if invalid JSON-LD dialect is detected
1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 |
# File 'lib/rdf/tabular/metadata.rb', line 1171 def normalize_jsonld(property, value) case value when Array value.map {|v| normalize_jsonld(property, v)} when String ev = {'@value' => value} ev['@language'] = context.default_language if context.default_language ev when Hash if value['@value'] if !(value.keys.sort - %w(@value @type @language)).empty? raise Error, "Value object may not contain keys other than @value, @type, or @language: #{value.to_json}" elsif (value.keys.sort & %w(@language @type)) == %w(@language @type) raise Error, "Value object may not contain both @type and @language: #{value.to_json}" elsif value['@language'] && !BCP47::Language.identify(value['@language']) raise Error, "Value object with @language must use valid language: #{value.to_json}" elsif value['@type'] && !context.(value['@type'], vocab: true).absolute? raise Error, "Value object with @type must defined type: #{value.to_json}" end value else nv = {} value.each do |k, v| case k when "@id" nv[k] = context.(v, documentRelative: true).to_s raise Error, "Invalid use of explicit BNode on @id" if nv[k].start_with?('_:') when "@type" Array(v).each do |vv| # Validate that all type values transform to absolute IRIs resource = context.(vv, vocab: true) raise Error, "Invalid type #{vv} in JSON-LD context" unless resource.uri? && resource.absolute? end nv[k] = v when /^(@|_:)/ raise Error, "Invalid use of #{k} in JSON-LD content" else nv[k] = normalize_jsonld(k, v) end end nv end else value end end |
#to_json(args = nil) ⇒ Object
1090 |
# File 'lib/rdf/tabular/metadata.rb', line 1090 def to_json(args=nil); object.to_json(args); end |
#type ⇒ :TableGroup, ...
Type of this Metadata
442 |
# File 'lib/rdf/tabular/metadata.rb', line 442 def type; self.class.name.split('::').last.to_sym; end |
#valid? ⇒ Boolean
Do we have valid metadata?
450 451 452 453 454 455 |
# File 'lib/rdf/tabular/metadata.rb', line 450 def valid? validate! true rescue false end |
#valid_inherited_property?(key, value) { ... } ⇒ Boolean
Determine if an inherited property is valid
715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 |
# File 'lib/rdf/tabular/metadata.rb', line 715 def valid_inherited_property?(key, value) pv = parent.send(key) if parent error = case key when :aboutUrl, :default, :propertyUrl, :valueUrl "string" unless value.is_a?(String) when :datatype # Normalization usually redundant dt = normalize_datatype(value) # FIXME: support arrays of datatypes? "valid datatype" unless DATATYPES.keys.map(&:to_s).include?(dt[:base]) || RDF::URI(dt[:base]).absolute? when :lang "valid BCP47 language tag" unless BCP47::Language.identify(value.to_s) when :null # To be valid, it must be a string or array, and must be compatible with any inherited value through being a subset "string or array of strings" unless !value.is_a?(Hash) && Array(value).all? {|v| v.is_a?(String)} when :ordered "boolean" unless value.is_a?(TrueClass) || value.is_a?(FalseClass) when :separator "single character" unless value.nil? || value.is_a?(String) && value.length == 1 when :textDirection # A value for this property is compatible with an inherited value only if they are identical. "rtl or ltr" unless %(rtl ltr).include?(value) end || case key # Compatibility when :aboutUrl, :propertyUrl, :valueUrl # No restrictions when :default, :ordered, :separator, :textDirection "same as that defined on parent" if pv && pv != value when :datatype if pv # Normalization usually redundant dt = normalize_datatype(value) pvdt = normalize_datatype(pv) vl = RDF::Literal.new("", datatype: DATATYPES[dt[:base].to_sym]) pvvl = RDF::Literal.new("", datatype: DATATYPES[pvdt[:base].to_sym]) # must be a subclass of some type defined on parent "compatible datatype of that defined on parent" unless vl.is_a?(pvvl.class) end when :lang "lang expected to restrict #{pv}" if pv && !value.start_with?(pv) when :null "subset of that defined on parent" if pv && (Array(value) & Array(pv)) != Array(value) end if error yield "#{type} has invalid property '#{key}' ('#{value}'): expected #{error}" false else true end end |
#valid_natural_language_property?(key, value) { ... } ⇒ Boolean
Determine if a natural language property is valid
703 704 705 706 707 708 |
# File 'lib/rdf/tabular/metadata.rb', line 703 def valid_natural_language_property?(key, value) unless value.is_a?(Hash) && value.all? {|k, v| Array(v).all? {|vv| vv.is_a?(String)}} yield "#{type} has invalid property '#{key}': #{value.inspect}, expected a valid natural language property" if block_given? false end end |
#validate! ⇒ self
Validate metadata, raising an error containing all errors detected during validation
470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 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 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 |
# File 'lib/rdf/tabular/metadata.rb', line 470 def validate! expected_props, required_props = @properties.keys, @required errors = [] unless is_a?(Dialect) || is_a?(Transformation) expected_props = expected_props + INHERITED_PROPERTIES.keys end # It has only expected properties (exclude metadata) check_keys = object.keys - [:"@id", :"@context"] check_keys = check_keys.reject {|k| k.to_s.include?(':')} unless is_a?(Dialect) errors << "#{type} has unexpected keys: #{(check_keys - expected_props).map(&:to_s)}" unless check_keys.all? {|k| expected_props.include?(k)} # It has required properties errors << "#{type} missing required keys: #{(required_props & check_keys).map(&:to_s)}" unless (required_props & check_keys) == required_props # Every property is valid object.keys.each do |key| value = object[key] case key when :aboutUrl, :datatype, :default, :lang, :null, :ordered, :propertyUrl, :separator, :textDirection, :valueUrl valid_inherited_property?(key, value) {|m| errors << m} when :columns if value.is_a?(Array) && value.all? {|v| v.is_a?(Column)} value.each do |v| begin v.validate! rescue Error => e errors << e. end end column_names = value.map(&:name) errors << "#{type} has invalid property '#{key}': must have unique names: #{column_names.inspect}" unless column_names.uniq == column_names else errors << "#{type} has invalid property '#{key}': expected array of Columns" end when :commentPrefix, :delimiter, :quoteChar unless value.is_a?(String) && value.length == 1 errors << "#{type} has invalid property '#{key}': #{value.inspect}, expected a single character string" end when :format, :lineTerminator, :uriTemplate unless value.is_a?(String) errors << "#{type} has invalid property '#{key}': #{value.inspect}, expected a string" end when :dialect unless value.is_a?(Dialect) errors << "#{type} has invalid property '#{key}': expected a Dialect Description" end begin value.validate! if value rescue Error => e errors << e. end when :doubleQuote, :header, :required, :skipInitialSpace, :skipBlankRows, :suppressOutput, :virtual unless value.is_a?(TrueClass) || value.is_a?(FalseClass) errors << "#{type} has invalid property '#{key}': #{value}, expected boolean true or false" end when :encoding unless (Encoding.find(value) rescue false) errors << "#{type} has invalid property '#{key}': #{value.inspect}, expected a valid encoding" end when :foreignKeys # An array of foreign key definitions that define how the values from specified columns within this table link to rows within this table or other tables. A foreign key definition is a JSON object with the properties: value.is_a?(Array) && value.each do |fk| if fk.is_a?(Hash) columnReference, reference = fk['columnReference'], fk['reference'] errors << "#{type} has invalid property '#{key}': missing columnReference and reference" unless columnReference && reference errors << "#{type} has invalid property '#{key}': has extra entries #{fk.keys.inspect}" unless fk.keys.length == 2 # Verify that columns exist in this schema Array(columnReference).each do |k| errors << "#{type} has invalid property '#{key}': columnReference not found #{k}" unless self.columns.any? {|c| c.name == k} end if reference.is_a?(Hash) ref_cols = reference['columnReference'] schema = if reference.has_key?('resource') if reference.has_key?('schemaReference') errors << "#{type} has invalid property '#{key}': reference has a schemaReference: #{reference.inspect}" end # resource is the URL of a Table in the TableGroup ref = base.join(reference['resource']).to_s table = root.is_a?(TableGroup) && root.resources.detect {|t| t.url == ref} errors << "#{type} has invalid property '#{key}': table referenced by #{ref} not found" unless table table.tableSchema if table elsif reference.has_key?('schemaReference') # resource is the @id of a Schema in the TableGroup ref = base.join(reference['schemaReference']).to_s tables = root.is_a?(TableGroup) ? root.resources.select {|t| t.tableSchema[:@id] == ref} : [] case tables.length when 0 errors << "#{type} has invalid property '#{key}': schema referenced by #{ref} not found" nil when 1 tables.first.tableSchema else errors << "#{type} has invalid property '#{key}': multiple schemas found from #{ref}" nil end end if schema # ref_cols must exist in schema Array(ref_cols).each do |k| errors << "#{type} has invalid property '#{key}': column reference not found #{k}" unless schema.columns.any? {|c| c.name == k} end end else errors << "#{type} has invalid property '#{key}': reference must be an object #{reference.inspect}" end else errors << "#{type} has invalid property '#{key}': reference must be an object: #{reference.inspect}" end end when :headerColumnCount, :headerRowCount, :skipColumns, :skipRows unless value.is_a?(Numeric) && value.integer? && value > 0 errors << "#{type} has invalid property '#{key}': #{value.inspect} must be a positive integer" end when :length, :minLength, :maxLength unless value.is_a?(Numeric) && value.integer? && value > 0 errors << "#{type} has invalid property '#{key}': #{value.inspect}, expected a positive integer" end unless key == :length || value != object[:length] # Applications must raise an error if length, maxLength or minLength are specified and the cell value is not a list (ie separator is not specified), a string or one of its subtypes, or a binary value. errors << "#{type} has invalid property '#{key}': Use of both length and #{key} requires they be equal" end when :minimum, :maximum, :minInclusive, :maxInclusive, :minExclusive, :maxExclusive unless value.is_a?(Numeric) || RDF::Literal::Date.new(value.to_s).valid? || RDF::Literal::Time.new(value.to_s).valid? || RDF::Literal::DateTime.new(value.to_s).valid? errors << "#{type} has invalid property '#{key}': #{value}, expected numeric or valid date/time" end when :name unless value.is_a?(String) && name.match(NAME_SYNTAX) errors << "#{type} has invalid property '#{key}': #{value}, expected proper name format" end when :notes unless value.is_a?(Hash) || value.is_a?(Array) errors << "#{type} has invalid property '#{key}': #{value}, Object or Array" end begin normalize_jsonld(key, value) rescue Error => e errors << "#{type} has invalid content '#{key}': #{e.}" end when :primaryKey # A column reference property that holds either a single reference to a column description object or an array of references. Array(value).each do |k| errors << "#{type} has invalid property '#{key}': column reference not found #{k}" unless self.columns.any? {|c| c.name == k} end when :resources if value.is_a?(Array) && value.all? {|v| v.is_a?(Table)} value.each do |t| begin t.validate! rescue Error => e errors << e. end end else errors << "#{type} has invalid property '#{key}': expected array of Tables" end when :scriptFormat, :targetFormat unless RDF::URI(value).valid? errors << "#{type} has invalid property '#{key}': #{value.inspect}, expected valid absolute URL" end when :source unless %w(json rdf).include?(value) || value.nil? errors << "#{type} has invalid property '#{key}': #{value.inspect}, expected json or rdf" end when :tableDirection unless %w(rtl ltr default).include?(value) errors << "#{type} has invalid property '#{key}': #{value.inspect}, expected rtl, ltr, or default" end when :tableSchema if value.is_a?(Schema) begin value.validate! rescue Error => e errors << e. end else errors << "#{type} has invalid property '#{key}': expected Schema" end when :transformations if value.is_a?(Array) && value.all? {|v| v.is_a?(Transformation)} value.each do |t| begin t.validate! rescue Error => e errors << e. end end else errors << "#{type} has invalid property '#{key}': expected array of Transformations" end when :title valid_natural_language_property?(:title, value) {|m| errors << m} when :trim unless %w(true false 1 0 start end).include?(value.to_s.downcase) errors << "#{type} has invalid property '#{key}': #{value.inspect}, expected true, false, 1, 0, start or end" end when :url unless @url.valid? errors << "#{type} has invalid property '#{key}': #{value.inspect}, expected valid absolute URL" end when :@id, :@context # Skip these when :@type unless value.to_sym == type errors << "#{type} has invalid property '#{key}': #{value.inspect}, expected #{type}" end when ->(k) {key.to_s.include?(':')} begin normalize_jsonld(key, value) rescue Error => e errors << "#{type} has invalid content '#{key}': #{e.}" end else errors << "#{type} has invalid property '#{key}': unsupported property" end end raise Error, errors.join("\n") unless errors.empty? self end |