Overview
Psych is a YAML parser and emitter. Psych leverages libyaml [Home page: pyyaml.org/wiki/LibYAML] or [Git repo: github.com/zerotao/libyaml] for its YAML parsing and emitting capabilities. In addition to wrapping libyaml, Psych also knows how to serialize and de-serialize most Ruby objects to and from the YAML format.
I NEED TO PARSE OR EMIT YAML RIGHT NOW!
# Parse some YAML
Psych.load("--- foo") # => "foo"
# Emit some YAML
Psych.dump("foo") # => "--- foo\n...\n"
{ :a => 'b'}.to_yaml # => "---\n:a: b\n"
Got more time on your hands? Keep on reading!
YAML Parsing
Psych provides a range of interfaces for parsing a YAML document ranging from low level to high level, depending on your parsing needs. At the lowest level, is an event based parser. Mid level is access to the raw YAML AST, and at the highest level is the ability to unmarshal YAML to ruby objects.
Low level parsing
The lowest level parser should be used when the YAML input is already known, and the developer does not want to pay the price of building an AST or automatic detection and conversion to ruby objects. See Psych::Parser for more information on using the event based parser.
Mid level parsing
Psych provides access to an AST produced from parsing a YAML document. This tree is built using the Psych::Parser and Psych::TreeBuilder. The AST can be examined and manipulated freely. Please see Psych.parse_stream, Psych::Nodes, and Psych::Nodes::Node for more information on dealing with YAML syntax trees.
High level parsing
The high level YAML parser provided by Psych simply takes YAML as input and returns a Ruby data structure. For information on using the high level parser see Psych.load
YAML Emitting
Psych provides a range of interfaces ranging from low to high level for producing YAML documents. Very similar to the YAML parsing interfaces, Psych provides at the lowest level, an event based system, mid-level is building a YAML AST, and the highest level is converting a Ruby object straight to a YAML document.
Low level emitting
The lowest level emitter is an event based system. Events are sent to a Psych::Emitter object. That object knows how to convert the events to a YAML document. This interface should be used when document format is known in advance or speed is a concern. See Psych::Emitter for more information.
Mid level emitting
At the mid level is building an AST. This AST is exactly the same as the AST used when parsing a YAML document. Users can build an AST by hand and the AST knows how to emit itself as a YAML document. See Psych::Nodes, Psych::Nodes::Node, and Psych::TreeBuilder for more information on building a YAML AST.
High level emitting
The high level emitter has the easiest interface. Psych simply takes a Ruby data structure and converts it to a YAML document. See Psych.dump for more information on dumping a Ruby data structure.
YAML Ain't Markup Language
This module provides a Ruby interface for data serialization in YAML format.
The underlying implementation is the libyaml wrapper Psych.
Usage
Working with YAML can be very simple, for example:
require 'yaml' # STEP ONE, REQUIRE YAML!
# Parse a YAML string
YAML.load("--- foo") #=> "foo"
# Emit some YAML
YAML.dump("foo") # => "--- foo\n...\n"
{ :a => 'b'}.to_yaml # => "---\n:a: b\n"
Security
Do not use YAML to load untrusted data. Doing so is unsafe and could allow malicious input to execute arbitrary code inside your application. Please see doc/security.rdoc for more information.
History
Syck was the original for YAML implementation in Ruby's standard library developed by why the lucky stiff.
You can still use Syck, if you prefer, for parsing and emitting YAML, but you must install the 'syck' gem now in order to use it.
In older Ruby versions, ie. <= 1.9, Syck is still provided, however it was completely removed with the release of Ruby 2.0.0.
More info
For more advanced details on the implementation see Psych, and also check out yaml.org for spec details and other helpful information.
- A
- D
- L
- O
- P
- R
- T
VERSION | = | '2.0.0' |
The version is Psych you're using |
||
LIBYAML_VERSION | = | Psych.libyaml_version.join '.' |
The version of libyaml Psych is using |
||
DEPRECATED | = | __FILE__ |
# File ext/psych/lib/psych/deprecated.rb, line 41 def self.add_ruby_type type_tag, &block warn "#{caller[0]}: add_ruby_type is deprecated, use add_domain_type" if $VERBOSE domain = 'ruby.yaml.org,2002' key = ['tag', domain, type_tag].join ':' @domain_types[key] = [key, block] end
Psych.dump(o, options) → string of yaml
Psych.dump(o, io) → io object passed in
Psych.dump(o, io, options) → io object passed in Link
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.
Example:
# Dump an array, get back a YAML string
Psych.dump(['a', 'b']) # => "---\n- a\n- b\n"
# Dump an array to an IO object
Psych.dump(['a', 'b'], StringIO.new) # => #<StringIO:0x000001009d0890>
# Dump an array with indentation set
Psych.dump(['a', ['b']], :indentation => 3) # => "---\n- a\n- - b\n"
# Dump an array to an IO with indentation set
Psych.dump(['a', ['b']], StringIO.new, :indentation => 3)
Dump a list of objects as separate documents to a document stream.
Example:
Psych.dump_stream("foo\n ", {}) # => "--- ! \"foo\\n \"\n--- {}\n"
Returns the version of libyaml being used
Source: show
static VALUE libyaml_version(VALUE module) { int major, minor, patch; VALUE list[3]; yaml_get_version(&major, &minor, &patch); list[0] = INT2NUM((long)major); list[1] = INT2NUM((long)minor); list[2] = INT2NUM((long)patch); return rb_ary_new4((long)3, list); }
Load yaml
in to a Ruby data structure. If multiple documents
are provided, the object contained in the first document will be returned.
filename
will be used in the exception message if any
exception is raised while parsing.
Raises a Psych::SyntaxError when a YAML syntax error is detected.
Example:
Psych.load("--- a") # => 'a'
Psych.load("---\n - a\n - b") # => ['a', 'b']
begin
Psych.load("--- `", "file.txt")
rescue Psych::SyntaxError => ex
ex.file # => 'file.txt'
ex.message # => "(file.txt): found character that cannot start any token"
end
This method is deprecated, use ::load_stream instead.
Load the document contained in filename
. Returns the yaml
contained in filename
as a ruby object
Load multiple documents given in yaml
. Returns the parsed
documents as a list. If a block is given, each document will be converted
to ruby and passed to the block during parsing
Example:
Psych.load_stream("--- foo\n...\n--- bar\n...") # => ['foo', 'bar']
list = []
Psych.load_stream("--- foo\n...\n--- bar\n...") do |ruby|
list << ruby
end
list # => ['foo', 'bar']
Parse a YAML string in yaml
. Returns
the first object of a YAML AST.
filename
is used in the exception message if a Psych::SyntaxError is raised.
Raises a Psych::SyntaxError when a YAML syntax error is detected.
Example:
Psych.parse("---\n - a\n - b") # => #<Psych::Nodes::Sequence:0x00>
begin
Psych.parse("--- `", "file.txt")
rescue Psych::SyntaxError => ex
ex.file # => 'file.txt'
ex.message # => "(file.txt): found character that cannot start any token"
end
See Psych::Nodes for more information about YAML AST.
Parse a file at filename
. Returns the YAML AST.
Raises a Psych::SyntaxError when a YAML syntax error is detected.
Parse a YAML string in yaml
. Returns
the full AST for the YAML document. This method can
handle multiple YAML documents contained in
yaml
. filename
is used in the exception message
if a Psych::SyntaxError is raised.
If a block is given, a Psych::Nodes::Document node will be yielded to the block as it's being parsed.
Raises a Psych::SyntaxError when a YAML syntax error is detected.
Example:
Psych.parse_stream("---\n - a\n - b") # => #<Psych::Nodes::Stream:0x00>
Psych.parse_stream("--- a\n--- b") do |node|
node # => #<Psych::Nodes::Document:0x00>
end
begin
Psych.parse_stream("--- `", "file.txt")
rescue Psych::SyntaxError => ex
ex.file # => 'file.txt'
ex.message # => "(file.txt): found character that cannot start any token"
end
See Psych::Nodes for more information about YAML AST.
# File ext/psych/lib/psych.rb, line 202 def self.parse_stream yaml, filename = nil, &block if block_given? parser = Psych::Parser.new(Handlers::DocumentStream.new(&block)) parser.parse yaml, filename else parser = self.parser parser.parse yaml, filename parser.handler.root end end
Returns a default parser
# File ext/psych/lib/psych/deprecated.rb, line 61 def self.read_type_class type, reference warn "#{caller[0]}: read_type_class is deprecated" if $VERBOSE _, _, type, name = type.split ':', 4 reference = name.split('::').inject(reference) do |k,n| k.const_get(n.to_sym) end if name [type, reference] end