Snippet: Binary to YAML

Recently, I was looking for a piece of code that could easily convert a file to YAML data. Here is what I use now. It follows the format described in http://yaml.org/type/binary.html.

def binary_to_yaml(file, indent_level = 1)
  if File.exists?(file)
    indent = ""
    indent_level.times{ indent << " " }
    data = File.open(file,'rb').read
    #YAML Generic binary representation, see http://yaml.org/type/binary.html	
    "!binary |\n#{indent}#{&#91;data&#93;.pack('m').gsub(/\n/,"\n#{indent}")}\n"	
  end
end
&#91;/sourcecode&#93;

The indent level describes how many spaces should be prepended. A binary value for a key that is unnested should have indent level 1. See the example below:

&#91;sourcecode language="ruby"&#93;
user: # indent level 1
 name: John Doe # indent level 2
 address:
  street: Sunset Blvd # indent level 3
  number: 2034
 thumbnail: <%= binary_to_yaml('files/thumb.jpg',2) %> # indent level 2

user: # indent level 1
 name: Jane Doe # indent level 2
 ...

~ by moiristo on November 1, 2008.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: