本文簡要介紹ruby語言中 Psych.safe_dump 的用法。
用法
safe_dump(o) → string of yaml
safe_dump(o, options) → string of yaml
safe_dump(o, io) → io object passed in
safe_dump(o, io, options) → io object passed in
安全地將 Ruby 對象 o 轉儲到 YAML 字符串。可以傳入可選的options 來控製輸出格式。如果傳入 IO 對象,則 YAML 將轉儲到該 IO 對象。默認情況下,隻允許序列化以下類:
可以通過將這些類添加到permitted_classes 關鍵字參數來允許任意類。它們是添加劑。例如,要允許 Date 序列化:
Psych.safe_dump(yaml, permitted_classes: [Date])
現在除了上麵列出的類之外,還可以轉儲 Date 類。
如果對象包含不在 permitted_classes 列表中的類,則會引發 Psych::DisallowedClass 異常。
目前支持的選項有:
:indentation-
用於縮進的空格字符數。可接受的值應在
0..9範圍內,否則忽略選項。默認值:
2。 :line_width-
換行的最大字符。
默認值:
0(意思是“在 81 處換行”)。 :canonical-
編寫“canonical”
YAML形式(非常冗長,但嚴格正式)。默認值:
false。 :header-
在文檔開頭寫上
%YAML [version]。默認值:
false。
例子:
# 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)
相關用法
- Ruby Psych.safe_load用法及代碼示例
- Ruby Psych.parse用法及代碼示例
- Ruby Psych.unsafe_load用法及代碼示例
- Ruby Psych.dump用法及代碼示例
- Ruby Psych.parse_stream用法及代碼示例
- Ruby Psych.dump_stream用法及代碼示例
- Ruby Psych.load_stream用法及代碼示例
- Ruby Psych模塊用法及代碼示例
- Ruby PrettyPrint.current_group用法及代碼示例
- Ruby Pathname.<=>用法及代碼示例
- Ruby Pathname.children用法及代碼示例
- Ruby Process.groups用法及代碼示例
- Ruby Process.wait2用法及代碼示例
- Ruby Process.getpgrp用法及代碼示例
- Ruby Proc.eql?用法及代碼示例
- Ruby PTY.open用法及代碼示例
- Ruby PrettyPrint.genspace用法及代碼示例
- Ruby PKey.sign_raw用法及代碼示例
- Ruby Profiler模塊用法及代碼示例
- Ruby Process.setproctitle用法及代碼示例
- Ruby PPMethods.comma_breakable用法及代碼示例
- Ruby Process.setrlimit用法及代碼示例
- Ruby Proc.prc ==用法及代碼示例
- Ruby Profiler.raw_data用法及代碼示例
- Ruby Process.uid用法及代碼示例
注:本文由純淨天空篩選整理自ruby-lang.org大神的英文原創作品 Psych.safe_dump。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。
