Debian Codegraph @

ext/psych/lib/psych.rb

raw symbols SCIP
1 # frozen_string_literal: true
2 require_relative 'psych/versions'
3 case RUBY_ENGINE
4 when 'jruby'
5 require_relative 'psych_jars'
6 if JRuby::Util.respond_to?(:load_ext)
7 JRuby::Util.load_ext('org.jruby.ext.psych.PsychLibrary')
8 else
9 require 'java'; require 'jruby'
10 org.jruby.ext.psych.PsychLibrary.new.load(JRuby.runtime, false)
11 end
12 else
13 require 'psych.so'
14 end
15 require_relative 'psych/nodes'
16 require_relative 'psych/streaming'
17 require_relative 'psych/visitors'
18 require_relative 'psych/handler'
19 require_relative 'psych/tree_builder'
20 require_relative 'psych/parser'
21 require_relative 'psych/omap'
22 require_relative 'psych/set'
23 require_relative 'psych/coder'
24 require_relative 'psych/core_ext'
25 require_relative 'psych/stream'
26 require_relative 'psych/json/tree_builder'
27 require_relative 'psych/json/stream'
28 require_relative 'psych/handlers/document_stream'
29 require_relative 'psych/class_loader'
30
31 ###
32 # = Overview
33 #
34 # Psych is a YAML parser and emitter.
35 # Psych leverages libyaml [Home page: https://pyyaml.org/wiki/LibYAML]
36 # or [git repo: https://github.com/yaml/libyaml] for its YAML parsing
37 # and emitting capabilities. In addition to wrapping libyaml, Psych also
38 # knows how to serialize and de-serialize most Ruby objects to and from
39 # the YAML format.
40 #
41 # = I NEED TO PARSE OR EMIT YAML RIGHT NOW!
42 #
43 # # Parse some YAML
44 # Psych.load("--- foo") # => "foo"
45 #
46 # # Emit some YAML
47 # Psych.dump("foo") # => "--- foo\n...\n"
48 # { :a => 'b'}.to_yaml # => "---\n:a: b\n"
49 #
50 # Got more time on your hands? Keep on reading!
51 #
52 # == YAML Parsing
53 #
54 # Psych provides a range of interfaces for parsing a YAML document ranging from
55 # low level to high level, depending on your parsing needs. At the lowest
56 # level, is an event based parser. Mid level is access to the raw YAML AST,
57 # and at the highest level is the ability to unmarshal YAML to Ruby objects.
58 #
59 # == YAML Emitting
60 #
61 # Psych provides a range of interfaces ranging from low to high level for
62 # producing YAML documents. Very similar to the YAML parsing interfaces, Psych
63 # provides at the lowest level, an event based system, mid-level is building
64 # a YAML AST, and the highest level is converting a Ruby object straight to
65 # a YAML document.
66 #
67 # == High-level API
68 #
69 # === Parsing
70 #
71 # The high level YAML parser provided by Psych simply takes YAML as input and
72 # returns a Ruby data structure. For information on using the high level parser
73 # see Psych.load
74 #
75 # ==== Reading from a string
76 #
77 # Psych.safe_load("--- a") # => 'a'
78 # Psych.safe_load("---\n - a\n - b") # => ['a', 'b']
79 # # From a trusted string:
80 # Psych.load("--- !ruby/range\nbegin: 0\nend: 42\nexcl: false\n") # => 0..42
81 #
82 # ==== Reading from a file
83 #
84 # Psych.safe_load_file("data.yml", permitted_classes: [Date])
85 # Psych.load_file("trusted_database.yml")
86 #
87 # ==== Exception handling
88 #
89 # begin
90 # # The second argument changes only the exception contents
91 # Psych.parse("--- `", "file.txt")
92 # rescue Psych::SyntaxError => ex
93 # ex.file # => 'file.txt'
94 # ex.message # => "(file.txt): found character that cannot start any token"
95 # end
96 #
97 # === Emitting
98 #
99 # The high level emitter has the easiest interface. Psych simply takes a Ruby
100 # data structure and converts it to a YAML document. See Psych.dump for more
101 # information on dumping a Ruby data structure.
102 #
103 # ==== Writing to a string
104 #
105 # # Dump an array, get back a YAML string
106 # Psych.dump(['a', 'b']) # => "---\n- a\n- b\n"
107 #
108 # # Dump an array to an IO object
109 # Psych.dump(['a', 'b'], StringIO.new) # => #<StringIO:0x000001009d0890>
110 #
111 # # Dump an array with indentation set
112 # Psych.dump(['a', ['b']], :indentation => 3) # => "---\n- a\n- - b\n"
113 #
114 # # Dump an array to an IO with indentation set
115 # Psych.dump(['a', ['b']], StringIO.new, :indentation => 3)
116 #
117 # ==== Writing to a file
118 #
119 # Currently there is no direct API for dumping Ruby structure to file:
120 #
121 # File.open('database.yml', 'w') do |file|
122 # file.write(Psych.dump(['a', 'b']))
123 # end
124 #
125 # == Mid-level API
126 #
127 # === Parsing
128 #
129 # Psych provides access to an AST produced from parsing a YAML document. This
130 # tree is built using the Psych::Parser and Psych::TreeBuilder. The AST can
131 # be examined and manipulated freely. Please see Psych::parse_stream,
132 # Psych::Nodes, and Psych::Nodes::Node for more information on dealing with
133 # YAML syntax trees.
134 #
135 # ==== Reading from a string
136 #
137 # # Returns Psych::Nodes::Stream
138 # Psych.parse_stream("---\n - a\n - b")
139 #
140 # # Returns Psych::Nodes::Document
141 # Psych.parse("---\n - a\n - b")
142 #
143 # ==== Reading from a file
144 #
145 # # Returns Psych::Nodes::Stream
146 # Psych.parse_stream(File.read('database.yml'))
147 #
148 # # Returns Psych::Nodes::Document
149 # Psych.parse_file('database.yml')
150 #
151 # ==== Exception handling
152 #
153 # begin
154 # # The second argument changes only the exception contents
155 # Psych.parse("--- `", "file.txt")
156 # rescue Psych::SyntaxError => ex
157 # ex.file # => 'file.txt'
158 # ex.message # => "(file.txt): found character that cannot start any token"
159 # end
160 #
161 # === Emitting
162 #
163 # At the mid level is building an AST. This AST is exactly the same as the AST
164 # used when parsing a YAML document. Users can build an AST by hand and the
165 # AST knows how to emit itself as a YAML document. See Psych::Nodes,
166 # Psych::Nodes::Node, and Psych::TreeBuilder for more information on building
167 # a YAML AST.
168 #
169 # ==== Writing to a string
170 #
171 # # We need Psych::Nodes::Stream (not Psych::Nodes::Document)
172 # stream = Psych.parse_stream("---\n - a\n - b")
173 #
174 # stream.to_yaml # => "---\n- a\n- b\n"
175 #
176 # ==== Writing to a file
177 #
178 # # We need Psych::Nodes::Stream (not Psych::Nodes::Document)
179 # stream = Psych.parse_stream(File.read('database.yml'))
180 #
181 # File.open('database.yml', 'w') do |file|
182 # file.write(stream.to_yaml)
183 # end
184 #
185 # == Low-level API
186 #
187 # === Parsing
188 #
189 # The lowest level parser should be used when the YAML input is already known,
190 # and the developer does not want to pay the price of building an AST or
191 # automatic detection and conversion to Ruby objects. See Psych::Parser for
192 # more information on using the event based parser.
193 #
194 # ==== Reading to Psych::Nodes::Stream structure
195 #
196 # parser = Psych::Parser.new(TreeBuilder.new) # => #<Psych::Parser>
197 # parser = Psych.parser # it's an alias for the above
198 #
199 # parser.parse("---\n - a\n - b") # => #<Psych::Parser>
200 # parser.handler # => #<Psych::TreeBuilder>
201 # parser.handler.root # => #<Psych::Nodes::Stream>
202 #
203 # ==== Receiving an events stream
204 #
205 # recorder = Psych::Handlers::Recorder.new
206 # parser = Psych::Parser.new(recorder)
207 #
208 # parser.parse("---\n - a\n - b")
209 # recorder.events # => [list of [event, args] lists]
210 # # event is one of: Psych::Handler::EVENTS
211 # # args are the arguments passed to the event
212 #
213 # === Emitting
214 #
215 # The lowest level emitter is an event based system. Events are sent to a
216 # Psych::Emitter object. That object knows how to convert the events to a YAML
217 # document. This interface should be used when document format is known in
218 # advance or speed is a concern. See Psych::Emitter for more information.
219 #
220 # ==== Writing to a Ruby structure
221 #
222 # Psych.parser.parse("--- a") # => #<Psych::Parser>
223 #
224 # parser.handler.first # => #<Psych::Nodes::Stream>
225 # parser.handler.first.to_ruby # => ["a"]
226 #
227 # parser.handler.root.first # => #<Psych::Nodes::Document>
228 # parser.handler.root.first.to_ruby # => "a"
229 #
230 # # You can instantiate an Emitter manually
231 # Psych::Visitors::ToRuby.new.accept(parser.handler.root.first)
232 # # => "a"
233
234 module Psych
235 # The version of libyaml Psych is using
236 LIBYAML_VERSION = Psych.libyaml_version.join('.').freeze
237
238 ###
239 # Load +yaml+ in to a Ruby data structure. If multiple documents are
240 # provided, the object contained in the first document will be returned.
241 # +filename+ will be used in the exception message if any exception
242 # is raised while parsing. If +yaml+ is empty, it returns
243 # the specified +fallback+ return value, which defaults to +false+.
244 #
245 # Raises a Psych::SyntaxError when a YAML syntax error is detected.
246 #
247 # Example:
248 #
249 # Psych.unsafe_load("--- a") # => 'a'
250 # Psych.unsafe_load("---\n - a\n - b") # => ['a', 'b']
251 #
252 # begin
253 # Psych.unsafe_load("--- `", filename: "file.txt")
254 # rescue Psych::SyntaxError => ex
255 # ex.file # => 'file.txt'
256 # ex.message # => "(file.txt): found character that cannot start any token"
257 # end
258 #
259 # When the optional +symbolize_names+ keyword argument is set to a
260 # true value, returns symbols for keys in Hash objects (default: strings).
261 #
262 # Psych.unsafe_load("---\n foo: bar") # => {"foo"=>"bar"}
263 # Psych.unsafe_load("---\n foo: bar", symbolize_names: true) # => {:foo=>"bar"}
264 #
265 # Raises a TypeError when `yaml` parameter is NilClass
266 #
267 # NOTE: This method *should not* be used to parse untrusted documents, such as
268 # YAML documents that are supplied via user input. Instead, please use the
269 # load method or the safe_load method.
270 #
271 def self.unsafe_load yaml, filename: nil, fallback: false, symbolize_names: false, freeze: false, strict_integer: false
272 result = parse(yaml, filename: filename)
273 return fallback unless result
274 result.to_ruby(symbolize_names: symbolize_names, freeze: freeze, strict_integer: strict_integer)
275 end
276
277 ###
278 # Safely load the yaml string in +yaml+. By default, only the following
279 # classes are allowed to be deserialized:
280 #
281 # * TrueClass
282 # * FalseClass
283 # * NilClass
284 # * Integer
285 # * Float
286 # * String
287 # * Array
288 # * Hash
289 #
290 # Recursive data structures are not allowed by default. Arbitrary classes
291 # can be allowed by adding those classes to the +permitted_classes+ keyword argument. They are
292 # additive. For example, to allow Date deserialization:
293 #
294 # Psych.safe_load(yaml, permitted_classes: [Date])
295 #
296 # Now the Date class can be loaded in addition to the classes listed above.
297 #
298 # Aliases can be explicitly allowed by changing the +aliases+ keyword argument.
299 # For example:
300 #
301 # x = []
302 # x << x
303 # yaml = Psych.dump x
304 # Psych.safe_load yaml # => raises an exception
305 # Psych.safe_load yaml, aliases: true # => loads the aliases
306 #
307 # A Psych::DisallowedClass exception will be raised if the yaml contains a
308 # class that isn't in the +permitted_classes+ list.
309 #
310 # A Psych::AliasesNotEnabled exception will be raised if the yaml contains aliases
311 # but the +aliases+ keyword argument is set to false.
312 #
313 # +filename+ will be used in the exception message if any exception is raised
314 # while parsing.
315 #
316 # When the optional +symbolize_names+ keyword argument is set to a
317 # true value, returns symbols for keys in Hash objects (default: strings).
318 #
319 # Psych.safe_load("---\n foo: bar") # => {"foo"=>"bar"}
320 # Psych.safe_load("---\n foo: bar", symbolize_names: true) # => {:foo=>"bar"}
321 #
322 def self.safe_load yaml, permitted_classes: [], permitted_symbols: [], aliases: false, filename: nil, fallback: nil, symbolize_names: false, freeze: false, strict_integer: false
323 result = parse(yaml, filename: filename)
324 return fallback unless result
325
326 class_loader = ClassLoader::Restricted.new(permitted_classes.map(&:to_s),
327 permitted_symbols.map(&:to_s))
328 scanner = ScalarScanner.new class_loader, strict_integer: strict_integer
329 visitor = if aliases
330 Visitors::ToRuby.new scanner, class_loader, symbolize_names: symbolize_names, freeze: freeze
331 else
332 Visitors::NoAliasRuby.new scanner, class_loader, symbolize_names: symbolize_names, freeze: freeze
333 end
334 result = visitor.accept result
335 result
336 end
337
338 ###
339 # Load +yaml+ in to a Ruby data structure. If multiple documents are
340 # provided, the object contained in the first document will be returned.
341 # +filename+ will be used in the exception message if any exception
342 # is raised while parsing. If +yaml+ is empty, it returns
343 # the specified +fallback+ return value, which defaults to +false+.
344 #
345 # Raises a Psych::SyntaxError when a YAML syntax error is detected.
346 #
347 # Example:
348 #
349 # Psych.load("--- a") # => 'a'
350 # Psych.load("---\n - a\n - b") # => ['a', 'b']
351 #
352 # begin
353 # Psych.load("--- `", filename: "file.txt")
354 # rescue Psych::SyntaxError => ex
355 # ex.file # => 'file.txt'
356 # ex.message # => "(file.txt): found character that cannot start any token"
357 # end
358 #
359 # When the optional +symbolize_names+ keyword argument is set to a
360 # true value, returns symbols for keys in Hash objects (default: strings).
361 #
362 # Psych.load("---\n foo: bar") # => {"foo"=>"bar"}
363 # Psych.load("---\n foo: bar", symbolize_names: true) # => {:foo=>"bar"}
364 #
365 # Raises a TypeError when `yaml` parameter is NilClass. This method is
366 # similar to `safe_load` except that `Symbol` objects are allowed by default.
367 #
368 def self.load yaml, permitted_classes: [Symbol], permitted_symbols: [], aliases: false, filename: nil, fallback: nil, symbolize_names: false, freeze: false, strict_integer: false
369 safe_load yaml, permitted_classes: permitted_classes,
370 permitted_symbols: permitted_symbols,
371 aliases: aliases,
372 filename: filename,
373 fallback: fallback,
374 symbolize_names: symbolize_names,
375 freeze: freeze,
376 strict_integer: strict_integer
377 end
378
379 ###
380 # Parse a YAML string in +yaml+. Returns the Psych::Nodes::Document.
381 # +filename+ is used in the exception message if a Psych::SyntaxError is
382 # raised.
383 #
384 # Raises a Psych::SyntaxError when a YAML syntax error is detected.
385 #
386 # Example:
387 #
388 # Psych.parse("---\n - a\n - b") # => #<Psych::Nodes::Document:0x00>
389 #
390 # begin
391 # Psych.parse("--- `", filename: "file.txt")
392 # rescue Psych::SyntaxError => ex
393 # ex.file # => 'file.txt'
394 # ex.message # => "(file.txt): found character that cannot start any token"
395 # end
396 #
397 # See Psych::Nodes for more information about YAML AST.
398 def self.parse yaml, filename: nil
399 parse_stream(yaml, filename: filename) do |node|
400 return node
401 end
402
403 false
404 end
405
406 ###
407 # Parse a file at +filename+. Returns the Psych::Nodes::Document.
408 #
409 # Raises a Psych::SyntaxError when a YAML syntax error is detected.
410 def self.parse_file filename, fallback: false
411 result = File.open filename, 'r:bom|utf-8' do |f|
412 parse f, filename: filename
413 end
414 result || fallback
415 end
416
417 ###
418 # Returns a default parser
419 def self.parser
420 Psych::Parser.new(TreeBuilder.new)
421 end
422
423 ###
424 # Parse a YAML string in +yaml+. Returns the Psych::Nodes::Stream.
425 # This method can handle multiple YAML documents contained in +yaml+.
426 # +filename+ is used in the exception message if a Psych::SyntaxError is
427 # raised.
428 #
429 # If a block is given, a Psych::Nodes::Document node will be yielded to the
430 # block as it's being parsed.
431 #
432 # Raises a Psych::SyntaxError when a YAML syntax error is detected.
433 #
434 # Example:
435 #
436 # Psych.parse_stream("---\n - a\n - b") # => #<Psych::Nodes::Stream:0x00>
437 #
438 # Psych.parse_stream("--- a\n--- b") do |node|
439 # node # => #<Psych::Nodes::Document:0x00>
440 # end
441 #
442 # begin
443 # Psych.parse_stream("--- `", filename: "file.txt")
444 # rescue Psych::SyntaxError => ex
445 # ex.file # => 'file.txt'
446 # ex.message # => "(file.txt): found character that cannot start any token"
447 # end
448 #
449 # Raises a TypeError when NilClass is passed.
450 #
451 # See Psych::Nodes for more information about YAML AST.
452 def self.parse_stream yaml, filename: nil, &block
453 if block_given?
454 parser = Psych::Parser.new(Handlers::DocumentStream.new(&block))
455 parser.parse yaml, filename
456 else
457 parser = self.parser
458 parser.parse yaml, filename
459 parser.handler.root
460 end
461 end
462
463 ###
464 # call-seq:
465 # Psych.dump(o) -> string of yaml
466 # Psych.dump(o, options) -> string of yaml
467 # Psych.dump(o, io) -> io object passed in
468 # Psych.dump(o, io, options) -> io object passed in
469 #
470 # Dump Ruby object +o+ to a YAML string. Optional +options+ may be passed in
471 # to control the output format. If an IO object is passed in, the YAML will
472 # be dumped to that IO object.
473 #
474 # Currently supported options are:
475 #
476 # [<tt>:indentation</tt>] Number of space characters used to indent.
477 # Acceptable value should be in <tt>0..9</tt> range,
478 # otherwise option is ignored.
479 #
480 # Default: <tt>2</tt>.
481 # [<tt>:line_width</tt>] Max character to wrap line at.
482 #
483 # Default: <tt>0</tt> (meaning "wrap at 81").
484 # [<tt>:canonical</tt>] Write "canonical" YAML form (very verbose, yet
485 # strictly formal).
486 #
487 # Default: <tt>false</tt>.
488 # [<tt>:header</tt>] Write <tt>%YAML [version]</tt> at the beginning of document.
489 #
490 # Default: <tt>false</tt>.
491 #
492 # Example:
493 #
494 # # Dump an array, get back a YAML string
495 # Psych.dump(['a', 'b']) # => "---\n- a\n- b\n"
496 #
497 # # Dump an array to an IO object
498 # Psych.dump(['a', 'b'], StringIO.new) # => #<StringIO:0x000001009d0890>
499 #
500 # # Dump an array with indentation set
501 # Psych.dump(['a', ['b']], indentation: 3) # => "---\n- a\n- - b\n"
502 #
503 # # Dump an array to an IO with indentation set
504 # Psych.dump(['a', ['b']], StringIO.new, indentation: 3)
505 def self.dump o, io = nil, options = {}
506 if Hash === io
507 options = io
508 io = nil
509 end
510
511 visitor = Psych::Visitors::YAMLTree.create options
512 visitor << o
513 visitor.tree.yaml io, options
514 end
515
516 ###
517 # call-seq:
518 # Psych.safe_dump(o) -> string of yaml
519 # Psych.safe_dump(o, options) -> string of yaml
520 # Psych.safe_dump(o, io) -> io object passed in
521 # Psych.safe_dump(o, io, options) -> io object passed in
522 #
523 # Safely dump Ruby object +o+ to a YAML string. Optional +options+ may be passed in
524 # to control the output format. If an IO object is passed in, the YAML will
525 # be dumped to that IO object. By default, only the following
526 # classes are allowed to be serialized:
527 #
528 # * TrueClass
529 # * FalseClass
530 # * NilClass
531 # * Integer
532 # * Float
533 # * String
534 # * Array
535 # * Hash
536 #
537 # Arbitrary classes can be allowed by adding those classes to the +permitted_classes+
538 # keyword argument. They are additive. For example, to allow Date serialization:
539 #
540 # Psych.safe_dump(yaml, permitted_classes: [Date])
541 #
542 # Now the Date class can be dumped in addition to the classes listed above.
543 #
544 # A Psych::DisallowedClass exception will be raised if the object contains a
545 # class that isn't in the +permitted_classes+ list.
546 #
547 # Currently supported options are:
548 #
549 # [<tt>:indentation</tt>] Number of space characters used to indent.
550 # Acceptable value should be in <tt>0..9</tt> range,
551 # otherwise option is ignored.
552 #
553 # Default: <tt>2</tt>.
554 # [<tt>:line_width</tt>] Max character to wrap line at.
555 #
556 # Default: <tt>0</tt> (meaning "wrap at 81").
557 # [<tt>:canonical</tt>] Write "canonical" YAML form (very verbose, yet
558 # strictly formal).
559 #
560 # Default: <tt>false</tt>.
561 # [<tt>:header</tt>] Write <tt>%YAML [version]</tt> at the beginning of document.
562 #
563 # Default: <tt>false</tt>.
564 #
565 # Example:
566 #
567 # # Dump an array, get back a YAML string
568 # Psych.safe_dump(['a', 'b']) # => "---\n- a\n- b\n"
569 #
570 # # Dump an array to an IO object
571 # Psych.safe_dump(['a', 'b'], StringIO.new) # => #<StringIO:0x000001009d0890>
572 #
573 # # Dump an array with indentation set
574 # Psych.safe_dump(['a', ['b']], indentation: 3) # => "---\n- a\n- - b\n"
575 #
576 # # Dump an array to an IO with indentation set
577 # Psych.safe_dump(['a', ['b']], StringIO.new, indentation: 3)
578 def self.safe_dump o, io = nil, options = {}
579 if Hash === io
580 options = io
581 io = nil
582 end
583
584 visitor = Psych::Visitors::RestrictedYAMLTree.create options
585 visitor << o
586 visitor.tree.yaml io, options
587 end
588
589 ###
590 # Dump a list of objects as separate documents to a document stream.
591 #
592 # Example:
593 #
594 # Psych.dump_stream("foo\n ", {}) # => "--- ! \"foo\\n \"\n--- {}\n"
595 def self.dump_stream *objects
596 visitor = Psych::Visitors::YAMLTree.create({})
597 objects.each do |o|
598 visitor << o
599 end
600 visitor.tree.yaml
601 end
602
603 ###
604 # Dump Ruby +object+ to a JSON string.
605 def self.to_json object
606 visitor = Psych::Visitors::JSONTree.create
607 visitor << object
608 visitor.tree.yaml
609 end
610
611 ###
612 # Load multiple documents given in +yaml+. Returns the parsed documents
613 # as a list. If a block is given, each document will be converted to Ruby
614 # and passed to the block during parsing
615 #
616 # Example:
617 #
618 # Psych.load_stream("--- foo\n...\n--- bar\n...") # => ['foo', 'bar']
619 #
620 # list = []
621 # Psych.load_stream("--- foo\n...\n--- bar\n...") do |ruby|
622 # list << ruby
623 # end
624 # list # => ['foo', 'bar']
625 #
626 def self.load_stream yaml, filename: nil, fallback: [], **kwargs
627 result = if block_given?
628 parse_stream(yaml, filename: filename) do |node|
629 yield node.to_ruby(**kwargs)
630 end
631 else
632 parse_stream(yaml, filename: filename).children.map { |node| node.to_ruby(**kwargs) }
633 end
634
635 return fallback if result.is_a?(Array) && result.empty?
636 result
637 end
638
639 ###
640 # Load the document contained in +filename+. Returns the yaml contained in
641 # +filename+ as a Ruby object, or if the file is empty, it returns
642 # the specified +fallback+ return value, which defaults to +false+.
643 #
644 # NOTE: This method *should not* be used to parse untrusted documents, such as
645 # YAML documents that are supplied via user input. Instead, please use the
646 # safe_load_file method.
647 def self.unsafe_load_file filename, **kwargs
648 File.open(filename, 'r:bom|utf-8') { |f|
649 self.unsafe_load f, filename: filename, **kwargs
650 }
651 end
652
653 ###
654 # Safely loads the document contained in +filename+. Returns the yaml contained in
655 # +filename+ as a Ruby object, or if the file is empty, it returns
656 # the specified +fallback+ return value, which defaults to +false+.
657 # See safe_load for options.
658 def self.safe_load_file filename, **kwargs
659 File.open(filename, 'r:bom|utf-8') { |f|
660 self.safe_load f, filename: filename, **kwargs
661 }
662 end
663
664 ###
665 # Loads the document contained in +filename+. Returns the yaml contained in
666 # +filename+ as a Ruby object, or if the file is empty, it returns
667 # the specified +fallback+ return value, which defaults to +false+.
668 # See load for options.
669 def self.load_file filename, **kwargs
670 File.open(filename, 'r:bom|utf-8') { |f|
671 self.load f, filename: filename, **kwargs
672 }
673 end
674
675 # :stopdoc:
676 def self.add_domain_type domain, type_tag, &block
677 key = ['tag', domain, type_tag].join ':'
678 domain_types[key] = [key, block]
679 domain_types["tag:#{type_tag}"] = [key, block]
680 end
681
682 def self.add_builtin_type type_tag, &block
683 domain = 'yaml.org,2002'
684 key = ['tag', domain, type_tag].join ':'
685 domain_types[key] = [key, block]
686 end
687
688 def self.remove_type type_tag
689 domain_types.delete type_tag
690 end
691
692 def self.add_tag tag, klass
693 load_tags[tag] = klass.name
694 dump_tags[klass] = tag
695 end
696
697 class << self
698 if defined?(Ractor)
699 class Config
700 attr_accessor :load_tags, :dump_tags, :domain_types
701 def initialize
702 @load_tags = {}
703 @dump_tags = {}
704 @domain_types = {}
705 end
706 end
707
708 def config
709 Ractor.current[:PsychConfig] ||= Config.new
710 end
711
712 def load_tags
713 config.load_tags
714 end
715
716 def dump_tags
717 config.dump_tags
718 end
719
720 def domain_types
721 config.domain_types
722 end
723
724 def load_tags=(value)
725 config.load_tags = value
726 end
727
728 def dump_tags=(value)
729 config.dump_tags = value
730 end
731
732 def domain_types=(value)
733 config.domain_types = value
734 end
735 else
736 attr_accessor :load_tags
737 attr_accessor :dump_tags
738 attr_accessor :domain_types
739 end
740 end
741 self.load_tags = {}
742 self.dump_tags = {}
743 self.domain_types = {}
744 # :startdoc:
745 end