multi_xml 0.7.2 → 0.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,169 @@
1
+ require "cgi/escape"
2
+
3
+ module MultiXML
4
+ module Parsers
5
+ # Shared SAX handler logic for building hash trees from XML events.
6
+ #
7
+ # Provides a stack machine used by both NokogiriSax and LibxmlSax
8
+ # handlers. Parser-specific subclasses translate their native callbacks
9
+ # into calls on this entrypoint:
10
+ #
11
+ # - handle_start_element_ns(local, prefix, attr_tuples, ns_decls)
12
+ # where attr_tuples = [[attr_prefix_or_nil, local, value], ...]
13
+ # ns_decls = [[prefix_or_nil, uri], ...]
14
+ #
15
+ # @api private
16
+ module SaxHandler
17
+ # Initialize the handler state
18
+ #
19
+ # @api private
20
+ # @param mode [Symbol] Namespace handling mode
21
+ # @return [void]
22
+ def initialize_handler(mode)
23
+ @mode = mode
24
+ @result = {}
25
+ @stack = [@result]
26
+ @pending = []
27
+ end
28
+
29
+ # Get the parsed result
30
+ #
31
+ # @api private
32
+ # @return [Hash] the parsed hash
33
+ attr_reader :result
34
+
35
+ private
36
+
37
+ # Get the current element hash on top of the stack
38
+ #
39
+ # @api private
40
+ # @return [Hash] current hash being built
41
+ def current = @stack.last
42
+
43
+ # Entry point for namespace-aware start events
44
+ #
45
+ # @api private
46
+ # @param local [String] Local element name
47
+ # @param prefix [String, nil] Element namespace prefix
48
+ # @param attr_tuples [Array] Attributes as [prefix, local, value]
49
+ # @param ns_decls [Array] xmlns declarations as [prefix, uri] pairs
50
+ # @return [void]
51
+ def handle_start_element_ns(local, prefix, attr_tuples, ns_decls)
52
+ child = {TEXT_CONTENT_KEY => +""}
53
+ add_child_to_current(format_name(prefix, local), child)
54
+ @stack << child
55
+
56
+ @pending << build_pending_attrs(ns_decls, attr_tuples)
57
+ end
58
+
59
+ # Apply attributes and pop the current element from the stack
60
+ #
61
+ # @api private
62
+ # @return [void]
63
+ def handle_end_element
64
+ @pending.pop.each { |key, value| add_attr_to_current(key, value) }
65
+ strip_whitespace_content
66
+ @stack.pop
67
+ end
68
+
69
+ # Append text to the current element's content
70
+ #
71
+ # @api private
72
+ # @param text [String] Text to append
73
+ # @return [void]
74
+ def append_text(text)
75
+ current[TEXT_CONTENT_KEY] << text
76
+ end
77
+
78
+ # Build the list of attributes to apply at element-end
79
+ #
80
+ # @api private
81
+ # @param ns_decls [Array] xmlns declarations
82
+ # @param attr_tuples [Array] Attribute [prefix, local, value] tuples
83
+ # @return [Array<Array>] list of [key, value] pairs
84
+ def build_pending_attrs(ns_decls, attr_tuples)
85
+ preserved_ns_decls(ns_decls) + attr_tuples.map do |prefix, local, value|
86
+ [format_name(prefix, local), CGI.unescapeHTML(value)]
87
+ end
88
+ end
89
+
90
+ # Transform xmlns declarations into attribute pairs for :preserve mode
91
+ #
92
+ # @api private
93
+ # @param ns_decls [Array] Declarations as [prefix, uri]
94
+ # @return [Array<Array>] [xmlns key, uri] pairs (empty outside :preserve)
95
+ def preserved_ns_decls(ns_decls)
96
+ return [] unless @mode == :preserve
97
+
98
+ ns_decls.map { |prefix, uri| [prefix ? "xmlns:#{prefix}" : "xmlns", uri] }
99
+ end
100
+
101
+ # Produce a name string for a [prefix, local] tuple
102
+ #
103
+ # @api private
104
+ # @param prefix [String, nil] Namespace prefix
105
+ # @param local [String] Local part of the name
106
+ # @return [String] formatted name
107
+ def format_name(prefix, local)
108
+ (@mode == :preserve && prefix) ? "#{prefix}:#{local}" : local
109
+ end
110
+
111
+ # Add a child element to the current hash, folding on collision
112
+ #
113
+ # @api private
114
+ # @param name [String] Child element name
115
+ # @param child [Hash] Child hash to add
116
+ # @return [void]
117
+ def add_child_to_current(name, child)
118
+ existing = current[name]
119
+ current[name] = case existing
120
+ when Array then existing << child
121
+ when Hash then [existing, child]
122
+ else child
123
+ end
124
+ end
125
+
126
+ # Add an attribute value to the current hash (attr wins on collision)
127
+ #
128
+ # Attributes are applied at end_element, after children have already
129
+ # populated the hash. When an attribute collides with a child of the
130
+ # same local name, the attribute is placed first in the resulting
131
+ # array (matching DomParser / REXML behavior and existing tests).
132
+ #
133
+ # @api private
134
+ # @param key [String] Attribute key
135
+ # @param value [String] Attribute value
136
+ # @return [void]
137
+ def add_attr_to_current(key, value)
138
+ existing = current[key]
139
+ current[key] = case existing
140
+ when nil then value
141
+ when Array then insert_attribute_before_children(existing, value)
142
+ when Hash then [value, existing]
143
+ else [existing, value]
144
+ end
145
+ end
146
+
147
+ # Insert a later attribute before any child-element entries
148
+ #
149
+ # @api private
150
+ # @param values [Array] Existing colliding values
151
+ # @param value [String] Attribute value to insert
152
+ # @return [Array] Updated value list
153
+ def insert_attribute_before_children(values, value)
154
+ child_index = values.index { |entry| entry.is_a?(Hash) } || values.length
155
+ values.dup.insert(child_index, value)
156
+ end
157
+
158
+ # Remove empty or whitespace-only text content from the current hash
159
+ #
160
+ # @api private
161
+ # @return [void]
162
+ def strip_whitespace_content
163
+ content = current[TEXT_CONTENT_KEY]
164
+ should_remove = content.empty? || (current.size > 1 && content.strip.empty?)
165
+ current.delete(TEXT_CONTENT_KEY) if should_remove
166
+ end
167
+ end
168
+ end
169
+ end
@@ -1,3 +1,7 @@
1
- module MultiXml
2
- VERSION = Gem::Version.create("0.7.2")
1
+ module MultiXML
2
+ # The current version of MultiXML
3
+ #
4
+ # @api public
5
+ # @return [Gem::Version] the gem version
6
+ VERSION = Gem::Version.create("0.9.1")
3
7
  end
data/lib/multi_xml.rb CHANGED
@@ -3,309 +3,206 @@ require "date"
3
3
  require "stringio"
4
4
  require "time"
5
5
  require "yaml"
6
-
7
- module MultiXml # rubocop:disable Metrics/ModuleLength
8
- class ParseError < StandardError; end
9
-
10
- class NoParserError < StandardError; end
11
-
12
- class DisallowedTypeError < StandardError
13
- def initialize(type)
14
- super("Disallowed type attribute: #{type.inspect}")
6
+ require_relative "multi_xml/concurrency"
7
+ require_relative "multi_xml/constants"
8
+ require_relative "multi_xml/errors"
9
+ require_relative "multi_xml/file_like"
10
+ require_relative "multi_xml/helpers"
11
+ require_relative "multi_xml/options"
12
+ require_relative "multi_xml/options_normalization"
13
+ require_relative "multi_xml/parser"
14
+ require_relative "multi_xml/parser_resolution"
15
+ require_relative "multi_xml/parse_support"
16
+
17
+ # A generic swappable back-end for parsing XML
18
+ #
19
+ # MultiXML provides a unified interface for XML parsing across different
20
+ # parser libraries. It automatically selects the best available parser
21
+ # (Ox, LibXML, Nokogiri, Oga, or REXML) and converts XML to Ruby hashes.
22
+ #
23
+ # @api public
24
+ # @example Parse XML
25
+ # MultiXML.parse('<root><name>John</name></root>')
26
+ # #=> {"root"=>{"name"=>"John"}}
27
+ #
28
+ # @example Set the parser
29
+ # MultiXML.parser = :nokogiri
30
+ module MultiXML
31
+ extend Options
32
+
33
+ # Tracks which deprecation warnings have already been emitted so each
34
+ # one fires at most once per process. Stored as a Set rather than a
35
+ # Hash so presence checks have unambiguous semantics for mutation tests.
36
+ DEPRECATION_WARNINGS_SHOWN = Set.new
37
+ private_constant :DEPRECATION_WARNINGS_SHOWN
38
+
39
+ # Emit a deprecation warning at most once per process for the given key
40
+ #
41
+ # The warning is tagged with the :deprecated category so callers can
42
+ # silence the whole set with Warning[:deprecated] = false or surface
43
+ # it via ruby -W:deprecated — the standard Ruby idiom for library
44
+ # deprecations since 2.7.
45
+ #
46
+ # @api private
47
+ # @param key [Symbol] identifier for the deprecation (typically the method name)
48
+ # @param message [String] warning message to emit on first call
49
+ # @return [void]
50
+ def self.warn_deprecation_once(key, message)
51
+ Concurrency.synchronize(:deprecation_warnings) do
52
+ return if DEPRECATION_WARNINGS_SHOWN.include?(key)
53
+
54
+ Kernel.warn(message, category: :deprecated)
55
+ DEPRECATION_WARNINGS_SHOWN.add(key)
15
56
  end
16
57
  end
17
58
 
18
- unless defined?(REQUIREMENT_MAP)
19
- REQUIREMENT_MAP = [
20
- ["ox", :ox],
21
- ["libxml", :libxml],
22
- ["nokogiri", :nokogiri],
23
- ["rexml/document", :rexml],
24
- ["oga", :oga]
25
- ].freeze
26
- end
27
-
28
- CONTENT_ROOT = "__content__".freeze unless defined?(CONTENT_ROOT)
29
-
30
- unless defined?(PARSING)
31
- float_proc = proc { |float| float.to_f }
32
- datetime_proc = proc { |time| Time.parse(time).utc rescue DateTime.parse(time).utc } # rubocop:disable Style/RescueModifier
33
-
34
- PARSING = {
35
- "symbol" => proc { |symbol| symbol.to_sym },
36
- "date" => proc { |date| Date.parse(date) },
37
- "datetime" => datetime_proc,
38
- "dateTime" => datetime_proc,
39
- "integer" => proc { |integer| integer.to_i },
40
- "float" => float_proc,
41
- "double" => float_proc,
42
- "decimal" => proc { |number| BigDecimal(number) },
43
- "boolean" => proc { |boolean| !%w[0 false].include?(boolean.strip) },
44
- "string" => proc { |string| string.to_s },
45
- "yaml" => proc { |yaml| YAML.load(yaml) rescue yaml }, # rubocop:disable Style/RescueModifier
46
- "base64Binary" => proc { |binary| base64_decode(binary) },
47
- "binary" => proc { |binary, entity| parse_binary(binary, entity) },
48
- "file" => proc { |file, entity| parse_file(file, entity) }
49
- }.freeze
50
- end
51
-
52
- unless defined?(TYPE_NAMES)
53
- TYPE_NAMES = {
54
- "Symbol" => "symbol",
55
- "Integer" => "integer",
56
- "BigDecimal" => "decimal",
57
- "Float" => "float",
58
- "TrueClass" => "boolean",
59
- "FalseClass" => "boolean",
60
- "Date" => "date",
61
- "DateTime" => "datetime",
62
- "Time" => "datetime",
63
- "Array" => "array",
64
- "Hash" => "hash"
65
- }.freeze
66
- end
67
-
68
- DISALLOWED_XML_TYPES = %w[symbol yaml].freeze
69
-
70
- DEFAULT_OPTIONS = {
71
- typecast_xml_value: true,
72
- disallowed_types: DISALLOWED_XML_TYPES,
73
- symbolize_keys: false
74
- }.freeze
75
-
76
59
  class << self
77
- # Get the current parser class.
78
- def parser
79
- return @parser if defined?(@parser)
60
+ include Helpers
61
+ include ParserResolution
62
+ include ParseSupport
80
63
 
81
- self.parser = default_parser
82
- @parser
83
- end
84
-
85
- # The default parser based on what you currently
86
- # have loaded and installed. First checks to see
87
- # if any parsers are already loaded, then checks
88
- # to see which are installed if none are loaded.
89
- def default_parser
90
- return :ox if defined?(::Ox)
91
- return :libxml if defined?(::LibXML)
92
- return :nokogiri if defined?(::Nokogiri)
93
- return :oga if defined?(::Oga)
94
-
95
- REQUIREMENT_MAP.each do |library, parser|
96
- require library
97
- return parser
98
- rescue LoadError
99
- next
100
- end
101
- raise(NoParserError,
102
- "No XML parser detected. If you're using Rubinius and Bundler, try adding an XML parser to your Gemfile (e.g. libxml-ruby, nokogiri, or rubysl-rexml). For more information, see https://github.com/sferik/multi_xml/issues/42.")
103
- end
104
-
105
- # Set the XML parser utilizing a symbol, string, or class.
106
- # Supported by default are:
107
- #
108
- # * <tt>:libxml</tt>
109
- # * <tt>:nokogiri</tt>
110
- # * <tt>:ox</tt>
111
- # * <tt>:rexml</tt>
112
- # * <tt>:oga</tt>
113
- def parser=(new_parser)
114
- case new_parser
115
- when String, Symbol
116
- require "multi_xml/parsers/#{new_parser.to_s.downcase}"
117
- @parser = MultiXml::Parsers.const_get(new_parser.to_s.split("_").collect(&:capitalize).join.to_s)
118
- when Class, Module
119
- @parser = new_parser
120
- else
121
- raise("Did not recognize your parser specification. Please specify either a symbol or a class.")
122
- end
123
- end
124
-
125
- # Parse an XML string or IO into Ruby.
64
+ # Get the current XML parser module
126
65
  #
127
- # <b>Options</b>
66
+ # Returns the currently configured parser, auto-detecting one if not set.
67
+ # Parsers are checked in order of performance: Ox, LibXML, Nokogiri, Oga, REXML.
128
68
  #
129
- # <tt>:symbolize_keys</tt> :: If true, will use symbols instead of strings for the keys.
69
+ # @api public
70
+ # @return [Module] the current parser module
71
+ # Honors a fiber-local override set by {.with_parser} so concurrent
72
+ # blocks observe their own parser without clobbering the process-wide
73
+ # default. Falls back to the process default when no override is set.
130
74
  #
131
- # <tt>:disallowed_types</tt> :: Types to disallow from being typecasted. Defaults to `['yaml', 'symbol']`. Use `[]` to allow all types.
132
- #
133
- # <tt>:typecast_xml_value</tt> :: If true, won't typecast values for parsed document
134
- def parse(xml, options = {}) # rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/MethodLength, Metrics/PerceivedComplexity
135
- xml ||= ""
136
-
137
- options = DEFAULT_OPTIONS.merge(options)
138
-
139
- xml = xml.strip if xml.respond_to?(:strip)
140
- begin
141
- xml = StringIO.new(xml) unless xml.respond_to?(:read)
142
-
143
- char = xml.getc
144
- return {} if char.nil?
145
-
146
- xml.ungetc(char)
147
-
148
- hash = undasherize_keys(parser.parse(xml) || {})
149
- hash = typecast_xml_value(hash, options[:disallowed_types]) if options[:typecast_xml_value]
150
- rescue DisallowedTypeError
151
- raise
152
- rescue parser.parse_error => e
153
- raise(ParseError, e.message, e.backtrace)
154
- end
155
- hash = symbolize_keys(hash) if options[:symbolize_keys]
156
- hash
157
- end
158
-
159
- # This module decorates files with the <tt>original_filename</tt>
160
- # and <tt>content_type</tt> methods.
161
- module FileLike # :nodoc:
162
- attr_writer :original_filename, :content_type
163
-
164
- def original_filename
165
- @original_filename || "untitled"
166
- end
167
-
168
- def content_type
169
- @content_type || "application/octet-stream"
170
- end
171
- end
172
-
173
- private
75
+ # @example Get current parser
76
+ # MultiXML.parser #=> MultiXML::Parsers::Ox
77
+ def parser
78
+ override = Fiber[:multi_xml_parser]
79
+ return override if override
174
80
 
175
- # TODO: Add support for other encodings
176
- def parse_binary(binary, entity) # :nodoc:
177
- case entity["encoding"]
178
- when "base64"
179
- base64_decode(binary)
180
- else
181
- binary
182
- end
81
+ @parser ||= resolve_parser(detect_parser)
183
82
  end
184
83
 
185
- def parse_file(file, entity)
186
- f = StringIO.new(base64_decode(file))
187
- f.extend(FileLike)
188
- f.original_filename = entity["name"]
189
- f.content_type = entity["content_type"]
190
- f
84
+ # Set the XML parser to use
85
+ #
86
+ # @api public
87
+ # @param new_parser [Symbol, String, Module] Parser specification
88
+ # - Symbol/String: :libxml, :nokogiri, :ox, :rexml, :oga
89
+ # - Module: Custom parser implementing parse(io) or
90
+ # parse(io, namespaces: ...) and parse_error
91
+ # @return [Module] the newly configured parser module
92
+ # @example Set parser by symbol
93
+ # MultiXML.parser = :nokogiri
94
+ # @example Set parser by module
95
+ # MultiXML.parser = MyCustomParser
96
+ def parser=(new_parser)
97
+ @parser = resolve_parser(new_parser)
191
98
  end
192
99
 
193
- def base64_decode(input)
194
- input.unpack1("m")
100
+ # Parse XML into a Ruby Hash
101
+ #
102
+ # @api public
103
+ # @param xml [String, IO] XML content as a string or IO-like object
104
+ # @param options [Hash] Parsing options
105
+ # @option options [Symbol, String, Module] :parser Parser to use for this call
106
+ # @option options [Boolean] :symbolize_names Convert keys to symbols (default: false)
107
+ # @option options [Array<String>] :disallowed_types Types to reject (default: ['yaml', 'symbol'])
108
+ # @option options [Boolean] :typecast_xml_value Apply type conversions (default: true)
109
+ # @option options [Symbol] :namespaces Namespace handling mode (:strip or :preserve)
110
+ # @return [Hash] Parsed XML as nested hash
111
+ # @raise [ParseError] if XML is malformed
112
+ # @raise [DisallowedTypeError] if XML contains a disallowed type attribute
113
+ # @example Parse simple XML
114
+ # MultiXML.parse('<root><name>John</name></root>')
115
+ # #=> {"root"=>{"name"=>"John"}}
116
+ # @example Parse with symbolized names
117
+ # MultiXML.parse('<root><name>John</name></root>', symbolize_names: true)
118
+ # #=> {root: {name: "John"}}
119
+ def parse(xml, options = {})
120
+ call_site = OptionsNormalization.normalize_symbolize_option(options)
121
+ global = OptionsNormalization.normalize_symbolize_option(parse_options(call_site))
122
+ options = DEFAULT_OPTIONS.merge(global, call_site)
123
+ namespaces = validate_namespaces_mode(options.fetch(:namespaces))
124
+ io = normalize_input(xml)
125
+ return {} if io.eof?
126
+
127
+ result = parse_with_error_handling(io, xml, resolve_parse_parser(options), namespaces)
128
+ apply_postprocessing(result, options)
195
129
  end
130
+ end
196
131
 
197
- def symbolize_keys(params)
198
- case params
199
- when Hash
200
- params.inject({}) do |result, (key, value)|
201
- result.merge(key.to_sym => symbolize_keys(value))
202
- end
203
- when Array
204
- params.collect { |value| symbolize_keys(value) }
205
- else
206
- params
207
- end
208
- end
132
+ # Execute a block with a temporarily-swapped parser
133
+ #
134
+ # The override is stored in fiber-local storage so concurrent fibers
135
+ # and threads each see their own parser without racing on a shared
136
+ # module variable; nested calls save and restore the previous
137
+ # fiber-local value. Matches {MultiJSON.with_adapter}.
138
+ #
139
+ # @api public
140
+ # @param new_parser [Symbol, String, Module] parser to use
141
+ # @yield block to execute with the temporary parser
142
+ # @return [Object] result of the block
143
+ # @example
144
+ # MultiXML.with_parser(:rexml) { MultiXML.parse("<a>1</a>") }
145
+ def self.with_parser(new_parser)
146
+ previous_override = Fiber[:multi_xml_parser]
147
+ Fiber[:multi_xml_parser] = resolve_parser(new_parser)
148
+ yield
149
+ ensure
150
+ Fiber[:multi_xml_parser] = previous_override
151
+ end
152
+ end
209
153
 
210
- def undasherize_keys(params)
211
- case params
212
- when Hash
213
- params.each_with_object({}) do |(key, value), hash|
214
- hash[key.to_s.tr("-", "_")] = undasherize_keys(value)
215
- hash
216
- end
217
- when Array
218
- params.collect { |value| undasherize_keys(value) }
219
- else
220
- params
221
- end
154
+ require_relative "multi_xml/deprecated"
155
+
156
+ # Backward-compatible alias for the legacy MultiXml constant name
157
+ #
158
+ # Downstream code that still writes MultiXml.parse(...) or
159
+ # rescue MultiXml::ParseError continues to work, but emits a one-time
160
+ # deprecation warning pointing at MultiXML. Each public method on
161
+ # {MultiXML} gets an explicit forwarder defined on this module, and
162
+ # constant access resolves via {.const_missing}, so both dotted calls
163
+ # and :: constant lookups (including rescue clauses) route through
164
+ # the canonical module.
165
+ #
166
+ # @api public
167
+ # @deprecated Use {MultiXML} (all-caps) instead. Will be removed in v1.0.
168
+ module MultiXml
169
+ # Forward every public method MultiXML exposes through an explicit
170
+ # singleton method on the legacy MultiXml module, so callers that
171
+ # capture the method as a Method object (``MultiXml.method(:load)``)
172
+ # find this forwarder instead of falling back to inherited methods like
173
+ # ``Kernel#load``. The earlier ``method_missing``-based shim left
174
+ # ``MultiXml.method(:load)`` resolving to ``Kernel#load`` (because
175
+ # ``Module#method`` doesn't consult ``method_missing``) so a captured
176
+ # ``MultiXml.method(:load)`` would interpret the XML payload as a file
177
+ # path and crash with ``LoadError``. Forwarding eagerly fixes the
178
+ # capture path while preserving the one-time deprecation warning each
179
+ # call emits.
180
+ (::MultiXML.public_methods - ::Module.public_methods).each do |forwarded|
181
+ define_singleton_method(forwarded) do |*args, **kwargs, &block|
182
+ ::MultiXML.warn_deprecation_once(:multi_xml_constant,
183
+ "The MultiXml constant is deprecated and will be removed in v1.0. Use MultiXML instead.")
184
+ ::MultiXML.public_send(forwarded, *args, **kwargs, &block)
222
185
  end
186
+ end
223
187
 
224
- def typecast_xml_value(value, disallowed_types = nil) # rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/MethodLength, Metrics/PerceivedComplexity
225
- disallowed_types ||= DISALLOWED_XML_TYPES
226
-
227
- case value
228
- when Hash
229
- if value.include?("type") && !value["type"].is_a?(Hash) && disallowed_types.include?(value["type"])
230
- raise(DisallowedTypeError, value["type"])
231
- end
232
-
233
- if value["type"] == "array"
234
-
235
- # this commented-out suggestion helps to avoid the multiple attribute
236
- # problem, but it breaks when there is only one item in the array.
237
- #
238
- # from: https://github.com/jnunemaker/httparty/issues/102
239
- #
240
- # _, entries = value.detect { |k, v| k != 'type' && v.is_a?(Array) }
241
-
242
- # This attempt fails to consider the order that the detect method
243
- # retrieves the entries.
244
- # _, entries = value.detect {|key, _| key != 'type'}
245
-
246
- # This approach ignores attribute entries that are not convertable
247
- # to an Array which allows attributes to be ignored.
248
- _, entries = value.detect { |k, v| k != "type" && (v.is_a?(Array) || v.is_a?(Hash)) }
249
-
250
- case entries
251
- when NilClass
252
- []
253
- when String
254
- [] if entries.strip.empty?
255
- when Array
256
- entries.collect { |entry| typecast_xml_value(entry, disallowed_types) }
257
- when Hash
258
- [typecast_xml_value(entries, disallowed_types)]
259
- else
260
- raise("can't typecast #{entries.class.name}: #{entries.inspect}")
261
- end
262
-
263
- elsif value.key?(CONTENT_ROOT)
264
- content = value[CONTENT_ROOT]
265
- block = PARSING[value["type"]]
266
- if block
267
- if block.arity == 1
268
- value.delete("type") if PARSING[value["type"]]
269
- if value.keys.size > 1
270
- value[CONTENT_ROOT] = block.call(content)
271
- value
272
- else
273
- block.call(content)
274
- end
275
- else
276
- block.call(content, value)
277
- end
278
- else
279
- (value.keys.size > 1) ? value : content
280
- end
281
- elsif value["type"] == "string" && value["nil"] != "true"
282
- ""
283
- # blank or nil parsed values are represented by nil
284
- elsif value.empty? || value["nil"] == "true"
285
- nil
286
- # If the type is the only element which makes it then
287
- # this still makes the value nil, except if type is
288
- # a XML node(where type['value'] is a Hash)
289
- elsif value["type"] && value.size == 1 && !value["type"].is_a?(Hash)
290
- nil
291
- else
292
- xml_value = value.each_with_object({}) do |(k, v), hash|
293
- hash[k] = typecast_xml_value(v, disallowed_types)
294
- hash
295
- end
296
-
297
- # Turn {:files => {:file => #<StringIO>} into {:files => #<StringIO>} so it is compatible with
298
- # how multipart uploaded files from HTML appear
299
- (xml_value["file"].is_a?(StringIO)) ? xml_value["file"] : xml_value
300
- end
301
- when Array
302
- value.map! { |i| typecast_xml_value(i, disallowed_types) }
303
- (value.length > 1) ? value : value.first
304
- when String
305
- value
306
- else
307
- raise("can't typecast #{value.class.name}: #{value.inspect}")
308
- end
188
+ class << self
189
+ # Resolve missing constants to their {MultiXML} counterparts
190
+ #
191
+ # The lookup is performed with ``inherit: false`` so a stray
192
+ # top-level ``::ParseError`` constant in the host process (Racc
193
+ # defines one when Nokogiri is loaded) is correctly ignored. Enables
194
+ # rescue MultiXml::ParseError and MultiXml::Parsers::Ox to keep
195
+ # working during the deprecation cycle.
196
+ #
197
+ # @api public
198
+ # @param name [Symbol] constant name
199
+ # @return [Object] the resolved constant from {MultiXML}
200
+ # @example
201
+ # MultiXml::Parsers::Ox # returns MultiXML::Parsers::Ox
202
+ def const_missing(name)
203
+ ::MultiXML.warn_deprecation_once(:multi_xml_constant,
204
+ "The MultiXml constant is deprecated and will be removed in v1.0. Use MultiXML instead.")
205
+ ::MultiXML.const_get(name, false)
309
206
  end
310
207
  end
311
208
  end