Class: XSD::BaseObject

Inherits:
Object
  • Object
show all
Defined in:
lib/xsd/base_object.rb,
sig/xsd.rbs

Overview

Base object

Constant Summary collapse

NO_ELEMENTS_CONTAINER =

Objects that can not have nested elements

Returns:

  • (::Array[:annotation | :simpleType | :attributeGroup | :attribute | :unique | :union | :simpleContent | :list | :any | :anyAttribute | :key | :keyref])
i[annotation simpleType attributeGroup attribute
unique union simpleContent list any anyAttribute key keyref].freeze
NO_ATTRIBUTES_CONTAINER =

Objects that cannot have nested attributes

Returns:

  • (::Array[:annotation | :unique | :anyAttribute | :all | :attribute | :choice | :sequence | :group | :simpleType | :facet | :key | :keyref])
i[annotation unique anyAttribute all
attribute choice sequence group simpleType facet key keyref].freeze
XML_SCHEMA =

Base XMLSchema namespace

Returns:

  • ("http://www.w3.org/2001/XMLSchema")
'http://www.w3.org/2001/XMLSchema'
XML_SCHEMA_NS =

Namespace map used for all internal xpath queries

Returns:

  • ({ "xs" => untyped })
{ 'xs' => XML_SCHEMA }.freeze
NOT_A_MEMBER =

What #read_member answers when the name is none of the object's members

Returns:

  • (Object)
Object.new.freeze

Class Attribute Summary collapse

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ BaseObject

Returns a new instance of BaseObject.

Parameters:

  • options (::Hash[untyped, untyped]) (defaults to: {})

Raises:



38
39
40
41
42
43
# File 'lib/xsd/base_object.rb', line 38

def initialize(options = {})
  raise Error, "#{self.class}.new expects a hash parameter" unless options.is_a?(Hash)

  @options = options
  @cache   = {}
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, *args) ⇒ Object

Lookup for properties

Parameters:

  • method (Symbol)
  • args (Array)

Returns:

  • (Object)


346
347
348
349
# File 'lib/xsd/base_object.rb', line 346

def method_missing(method, *args)
  value = read_member(method, args)
  value.equal?(NOT_A_MEMBER) ? super : value
end

Class Attribute Details

.children ⇒ Object (readonly)

Returns the value of attribute children.

Returns:

  • (Object)


23
24
25
# File 'lib/xsd/base_object.rb', line 23

def children
  @children
end

Returns the value of attribute links.

Returns:

  • (Object)


23
24
25
# File 'lib/xsd/base_object.rb', line 23

def links
  @links
end

.properties ⇒ Object (readonly)

Returns the value of attribute properties.

Returns:

  • (Object)


23
24
25
# File 'lib/xsd/base_object.rb', line 23

def properties
  @properties
end

Instance Attribute Details

#id ⇒ Object

Optional. Specifies a unique ID for the element property :id, :string

Returns:

  • String



61
62
63
# File 'lib/xsd/base_object.rb', line 61

def id
  node['id']
end

#options ⇒ Object (readonly)

Returns the value of attribute options.

Returns:

  • (Object)


6
7
8
# File 'lib/xsd/base_object.rb', line 6

def options
  @options
end

Class Method Details

.child(name, type, options = {}) ⇒ Object

Define new object child

Parameters:

  • name (Symbol)
  • type (Symbol, Array<Symbol>)
  • options (Hash) (defaults to: {})

Returns:

  • (Object)


296
297
298
299
300
301
302
303
# File 'lib/xsd/base_object.rb', line 296

def self.child(name, type, options = {})
  method = to_underscore(name)
  children[method] = {
    type: type,
    **options
  }
  define_member_reader(method)
end

.define_member_reader(method) ⇒ nil, untyped

A property, link or child is read through a method of its own: reaching it through method_missing costs far more per call, and an object is asked for its members all the time. The method goes in a module of the class's own, so that a method the class defines itself still wins, and is not defined where a method of that name exists already — an ancestor's own keeps answering, as it did when the name went to method_missing.

Parameters:

  • method (Symbol)

Returns:

  • (nil, untyped)


323
324
325
326
327
328
329
330
331
332
# File 'lib/xsd/base_object.rb', line 323

def self.define_member_reader(method)
  return if method_defined?(method) || private_method_defined?(method)

  member_readers.define_method(method) do |*args|
    value = read_member(method, args)
    raise NoMethodError.new("undefined method '#{method}' for an instance of #{self.class}", method) if value.equal?(NOT_A_MEMBER)

    value
  end
end

Define new object child

Parameters:

  • name (Symbol)
  • type (Symbol)
  • options (Hash) (defaults to: {})

Returns:

  • (Object)


309
310
311
312
313
314
315
316
# File 'lib/xsd/base_object.rb', line 309

def self.link(name, type, options = {})
  method = to_underscore(name)
  links[method] = {
    type: type,
    **options
  }
  define_member_reader(method)
end

.mapped_name ⇒ Object

Get mapped element name

Returns:

  • Symbol



400
401
402
403
404
405
406
# File 'lib/xsd/base_object.rb', line 400

def self.mapped_name
  @mapped_name ||= begin
    name = self.name.split('::').last
    name[0] = name[0].downcase
    name.to_sym
  end
end

.member_readers ⇒ Object

The module a class's member readers are defined in

Returns:

  • Module



336
337
338
# File 'lib/xsd/base_object.rb', line 336

def self.member_readers
  @member_readers ||= Module.new.tap { |readers| include(readers) }
end

.property(name, type, options = {}) {|arg0| ... } ⇒ Object

Define new object property

Parameters:

  • name (Symbol)
  • type (Symbol)
  • options (Hash) (defaults to: {})

Yields:

Yield Parameters:

  • arg0

Yield Returns:

  • (Object)

Returns:

  • (Object)


281
282
283
284
285
286
287
288
289
290
# File 'lib/xsd/base_object.rb', line 281

def self.property(name, type, options = {}, &block)
  method = to_underscore(name)
  properties[method] = {
    name: name,
    type: type,
    resolve: block,
    **options
  }
  define_member_reader(method)
end

.to_underscore(string) ⇒ Object

Parameters:

  • string (Object)

Returns:

  • (Object)


273
274
275
# File 'lib/xsd/base_object.rb', line 273

def self.to_underscore(string)
  string.to_s.gsub(/([^A-Z])([A-Z]+)/, '\1_\2').sub(':', '_').downcase.to_sym
end

Instance Method Details

#[](*args) ⇒ Object

Get element or attribute by path

Parameters:

  • args (Object)

Returns:

  • Element, Attribute, nil



99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
# File 'lib/xsd/base_object.rb', line 99

def [](*args)
  result = self

  args.flatten.each do |curname|
    next if result.nil?

    curname = curname.to_s

    if curname[0] == '@'
      result = result.collect_attributes.find { |attr| definition_match?(attr, curname[1..]) }
    else
      result = result.collect_elements.find { |elem| definition_match?(elem, curname) }
    end
  end

  result
end

#collect_attributes ⇒ Object

Get all available attributes on the current stack level

Parameters:

  • (Object)

Returns:

  • (Object)


247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
# File 'lib/xsd/base_object.rb', line 247

def collect_attributes(*)
  @collect_attributes ||= if NO_ATTRIBUTES_CONTAINER.include?(self.class.mapped_name)
                            []
                          elsif is_a?(Referenced) && ref
                            reference.collect_attributes
                          else
                            # map children recursive
                            map_children(:*).flat_map do |obj|
                              if obj.is_a?(Attribute) || obj.is_a?(AnyAttribute)
                                obj
                              else
                                # get attributes considering references
                                (obj.is_a?(Referenced) && obj.ref ? obj.reference : obj).collect_attributes
                              end
                            end
                          end
end

#collect_elements ⇒ Object

Get all available elements on the current stack level

Parameters:

  • (Object)

Returns:

  • (Object)


227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
# File 'lib/xsd/base_object.rb', line 227

def collect_elements(*)
  @collect_elements ||= if NO_ELEMENTS_CONTAINER.include?(self.class.mapped_name)
                          []
                        elsif is_a?(Referenced) && ref
                          reference.collect_elements
                        else
                          # map children recursive
                          map_children(:*).flat_map do |obj|
                            if obj.is_a?(Element) || obj.is_a?(Any)
                              obj
                            else
                              # get elements considering references
                              (obj.is_a?(Referenced) && obj.ref ? obj.reference : obj).collect_elements
                            end
                          end
                        end
end

#documentation ⇒ Object

Return element documentation

Returns:

  • (Object)


205
206
207
208
209
210
211
212
213
214
215
216
# File 'lib/xsd/base_object.rb', line 205

def documentation
  @documentation ||= begin
    docs = documentation_for(node)
    if docs.any?
      docs
    elsif is_a?(Referenced) && referenced?
      documentation_for(reference.node)
    else
      []
    end
  end
end

#documentation_for(node) ⇒ Object

Return documentation for specified node

Parameters:

  • node (Nokogiri::XML::Node)

Returns:

  • (Object)


221
222
223
# File 'lib/xsd/base_object.rb', line 221

def documentation_for(node)
  node.xpath('./xs:annotation/xs:documentation/text()', XML_SCHEMA_NS).map { |x| x.text.strip }
end

#get_prefix(name) ⇒ Object

Get namespace prefix from node name

Parameters:

  • name (String, nil) —

    Name to strip from

Returns:

  • String, nil



199
200
201
# File 'lib/xsd/base_object.rb', line 199

def get_prefix(name)
  name&.include?(':') ? name.split(':').first : nil
end

#inspect ⇒ Object

Get object string representation

Returns:

  • String



53
54
55
# File 'lib/xsd/base_object.rb', line 53

def inspect
  "#<#{self.class.name} path=#{node.path}>"
end

#map_child(name) ⇒ Object

Get child object

Parameters:

  • name (Symbol)

Returns:

  • BaseObject, nil



185
186
187
# File 'lib/xsd/base_object.rb', line 185

def map_child(name)
  map_children(name).first
end

#map_children(name) ⇒ Object

Get child objects

Parameters:

  • name (Symbol)

Returns:

  • (Object)


178
179
180
# File 'lib/xsd/base_object.rb', line 178

def map_children(name)
  nodes(name).map { |node| node_to_object(node) }
end

#namespaces ⇒ Object

Get current namespaces

Returns:

  • Hash



67
68
69
# File 'lib/xsd/base_object.rb', line 67

def namespaces
  node.namespaces || {}
end

#nil_if_empty(string) ⇒ Object

Return string if it is not empty, or nil otherwise

Parameters:

  • string (String, nil)

Returns:

  • String, nil



411
412
413
# File 'lib/xsd/base_object.rb', line 411

def nil_if_empty(string)
  string && string.empty? ? nil : string
end

#node ⇒ Object

Get current XML node

Returns:

  • Nokogiri::XML::Node



47
48
49
# File 'lib/xsd/base_object.rb', line 47

def node
  options[:node]
end

#node_to_object(node) ⇒ Object

Get reader object for node

Parameters:

  • node (Nokogiri::XML::Node)

Returns:

  • BaseObject



144
145
146
147
148
149
150
151
152
153
154
# File 'lib/xsd/base_object.rb', line 144

def node_to_object(node)
  # check object in cache first; a chameleon view keeps a cache of its own (see Schema#object_cache)
  cache = schema.object_cache
  cached = cache[node]
  return cached if cached

  klass = XML::CLASS_MAP[node.name]
  raise Error, "Object class not found for '#{node.name}'" unless klass

  cache[node] = klass.new(options.merge(node: node, schema: schema))
end

#nodes(name = :*, deep = false) ⇒ Object

Get child nodes

Parameters:

  • name (Symbol) (defaults to: :*)
  • deep (Boolean) (defaults to: false)

Returns:

  • Nokogiri::XML::NodeSet



75
76
77
# File 'lib/xsd/base_object.rb', line 75

def nodes(name = :*, deep = false)
  node.xpath("./#{'/' if deep}xs:#{name}", XML_SCHEMA_NS)
end

#object_by_name(node_name, name) ⇒ Object

Search node by name in all available schemas and return its object

Parameters:

  • node_name (Symbol)
  • name (String)

Returns:

  • BaseObject, nil



121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
# File 'lib/xsd/base_object.rb', line 121

def object_by_name(node_name, name)
  # get prefix and local name
  name_prefix = get_prefix(name)
  name_local  = strip_prefix(name)

  # do not search for built-in types
  return nil if schema.namespace_prefix == name_prefix

  # determine schema for namespace
  search_schemas = schemas_for_namespace(name_prefix)

  # find the declaration in the schemas of the namespace
  search_schemas.each do |s|
    node = s.declaration_node(node_name, name_local)
    return s.node_to_object(node) if node
  end

  nil
end

#parent ⇒ Object

Get xml parent object

Returns:

  • BaseObject, nil



158
159
160
161
162
163
164
165
166
167
# File 'lib/xsd/base_object.rb', line 158

def parent
  return @parent if defined?(@parent)

  parent_node = node.respond_to?(:parent) ? node.parent : nil

  # the parent may be a document or a node of a foreign schema (e.g. wsdl:types), there is no object for those
  @parent = if parent_node.is_a?(Nokogiri::XML::Element) && XML::CLASS_MAP.key?(parent_node.name)
              node_to_object(parent_node)
            end
end

#read_member(method, args) ⇒ Object

The value of a property, link or child, cached: from the node, through a reference, or by its name in the schemas. A member reader and method_missing both come here.

Parameters:

  • method (Symbol)
  • args (Array)

Returns:

  • Object, NOT_A_MEMBER



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/xsd/base_object.rb', line 356

def read_member(method, args)
  # check cache first, nil and false results are cached as well
  return @cache[method] if @cache.key?(method)

  # check for property first
  if (property = self.class.properties[method])
    return @cache[method] = property_value(property, method, args)
  end

  # if object has ref it cannot contain any type and children, so proxy call to target object
  if node['ref'] && method != :ref && method != :reference
    return @cache[method] = reference.send(method, *args)
  end

  # then check for linked types
  if (link = self.class.links[method])
    name = link[:property] ? send(link[:property]) : nil
    if name
      return @cache[method] = object_by_name(link[:type], name)
    elsif is_a?(Restriction) && i[base_simple_type base_complex_type].include?(method)
      # handle restriction without base
      return @cache[method] = nil
    end
  end

  # last check for nested objects
  if (child = self.class.children[method])
    result = child[:type].is_a?(Array) ? map_children(child[:type][0]) : map_child(child[:type])
    return @cache[method] = result
  end

  NOT_A_MEMBER
end

#reader ⇒ Object

Get reader instance

Returns:

  • XML



267
268
269
# File 'lib/xsd/base_object.rb', line 267

def reader
  options[:reader]
end

#respond_to_missing?(method, include_private = false) ⇒ Object

Does object has property/link/child?

Parameters:

  • method (Symbol)
  • include_private (Boolean) (defaults to: false)

Returns:

  • (Object)


393
394
395
396
# File 'lib/xsd/base_object.rb', line 393

def respond_to_missing?(method, include_private = false)
  !self.class.properties[method].nil? || !self.class.links[method].nil? ||
    !self.class.children[method].nil? || super
end

#schema ⇒ Object

Get current schema object

Returns:

  • Schema



171
172
173
# File 'lib/xsd/base_object.rb', line 171

def schema
  options[:schema]
end

#schemas_for_namespace(ns_or_prefix) ⇒ Object

Get schemas by namespace or prefix

Parameters:

  • ns_or_prefix (String, nil)

Returns:

  • (Object)


82
83
84
85
86
87
88
89
90
91
92
93
94
95
# File 'lib/xsd/base_object.rb', line 82

def schemas_for_namespace(ns_or_prefix)
  # resolve namespace for current node if prefix was provided
  prefix = namespaces[['xmlns', (ns_or_prefix == '' ? nil : ns_or_prefix)].compact.join(':')]
  ns = prefix || ns_or_prefix

  if schema.targets_namespace?(ns)
    schema.with_includes
  elsif (import = schema.import_by_namespace(ns))
    # what the imported schema includes is part of its namespace too
    import.imported_schema.with_includes
  else
    raise Error, "Schema not found for namespace '#{ns}' in '#{schema.id || schema.target_namespace}'"
  end
end

#strip_prefix(name) ⇒ Object

Strip namespace prefix from node name

Parameters:

  • name (String, nil) —

    Name to strip from

Returns:

  • String, nil



192
193
194
# File 'lib/xsd/base_object.rb', line 192

def strip_prefix(name)
  name&.include?(':') ? name.split(':').last : name
end