1. Computing

Serialization in Ruby: YAML

By

1 of 2

Serialization in Ruby: YAML

YAML (YAML Ain't Markup Language) is perhaps the most common form of serialization in Ruby applications. It's used for configuration files in Rails and other projects, and is nearly ubiquitous. It also has distinct advantages over marshal, and is usually preferred.

YAML is a plaintext format, as opposed to marshal's binary format. Immediately, this makes things easier. Your objects now stored as YAML are completely transparent and editable with nothing more than a text editor, someone everyone has on their computers. It also has a simple, spartan syntax that's easy to look at and easy to type. It isn't encumbered by excessive wordage and symbols seen in XML.

It's also quite easy to use, at least for simply storing and reading objects. There are some limitations, which is to be expected from any serialization library. Some objects have no meaning taken out of context. This includes Binding, Proc and IO objects. Be aware that anything but simple types (numbers, strings, arrays, hashes, or a composition of those) may not be represented fully in YAML. But it's rather easy to see if someone was represented fully, just look at the generated YAML in a text editor.

To take a quick look at what YAML can do, here is a simple counter example. It stores a single number in a file as YAML. To load from the file, YAML::load is used. To serialize an object, that object's to_yaml method is used. These are the only two methods you'll need to know for this use.


#!/usr/bin/env ruby
require 'yaml'

counter = if File.exists?('counter')
            YAML::load( File.read('counter') )
          else
            0
          end

puts "Counter is currently at #{counter}"
puts "incrementing to #{counter + 1}"

counter += 1

File.open('counter','w') do|file|
  file.puts counter.to_yaml
end

The counter variable is stored in a file called counter. This is a text file that looks something like this.


--- 10

As this is a single variable stored in a file, this isn't much to look at. But it does give quite a lot of insight into what YAML is and how it operates. Notice there is no mention of what type the variable is, or anything about it other than its value. YAML operates on assumptions, and while this might not be ideal in all situations, it's more than ideal in most situations.

Serialization Methods in Ruby
  1. About.com
  2. Computing
  3. Ruby
  4. Advanced Ruby
  5. Serialization
  6. Serialization in Ruby: YAML

©2014 About.com. All rights reserved.