End of Life Ruby 3.2 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →
Psych.safe_dump
# File tmp/rubies/ruby-3.2.0/ext/psych/lib/psych.rb, line 578
def self.safe_dump o, io = nil, options = {}
if Hash === io
options = io
io = nil
end
visitor = Psych::Visitors::RestrictedYAMLTree.create options
visitor << o
visitor.tree.yaml io, options
end
Safely dump Ruby object o to a YAML string. Optional options may be passed in to control the output format. If an IO object is passed in, the YAML will be dumped to that IO object. By default, only the following classes are allowed to be serialized:
Arbitrary classes can be allowed by adding those classes to the permitted_classes keyword argument. They are additive. For example, to allow Date serialization:
Psych.safe_dump(yaml, permitted_classes: [Date])
Now the Date class can be dumped in addition to the classes listed above.
A Psych::DisallowedClass exception will be raised if the object contains a class that isn’t in the permitted_classes list.
Currently supported options are:
:indentation-
Number of space characters used to indent. Acceptable value should be in
0..9range, otherwise option is ignored.Default:
2. :line_width-
Max character to wrap line at.
Default:
0(meaning “wrap at 81”). :canonical-
Write “canonical”
YAMLform (very verbose, yet strictly formal).Default:
false. :header-
Write
%YAML [version]at the beginning of document.Default:
false.
Example:
# Dump an array, get back a YAML string Psych.safe_dump(['a', 'b']) # => "---\n- a\n- b\n" # Dump an array to an IO object Psych.safe_dump(['a', 'b'], StringIO.new) # => #<StringIO:0x000001009d0890> # Dump an array with indentation set Psych.safe_dump(['a', ['b']], indentation: 3) # => "---\n- a\n- - b\n" # Dump an array to an IO with indentation set Psych.safe_dump(['a', ['b']], StringIO.new, indentation: 3)